     Home Search   What's New Index Books Links Q & A Newsletter Banners   Feedback Tip Jar      MSDN Visual Basic Community  Title Draw a fractal Hilbert curve in VB.NET This example shows how to draw a fractal Hilbert curve in VB.NET. fractal, Hilbert curve Graphics, VB.NET

The remarkably short Hilbert subroutine draws the Hilbert curve. It takes as parameters the depth of recursion, and dx and dy values that give the direction in which it should draw. It recursively draws four smaller Hilbert curves and connects them with lines.

```' Draw a Hilbert curve.
Private Sub Hilbert(ByVal gr As Graphics, ByVal depth As _
Integer, ByVal dx As Double, ByVal dy As Double)
If depth > 1 Then Hilbert(gr, depth - 1, dy, dx)
DrawRelative(gr, dx, dy)
If depth > 1 Then Hilbert(gr, depth - 1, dx, dy)
DrawRelative(gr, dy, dx)
If depth > 1 Then Hilbert(gr, depth - 1, dx, dy)
DrawRelative(gr, -dx, -dy)
If depth > 1 Then Hilbert(gr, depth - 1, -dy, -dx)

If m_Refresh Then picCanvas.Refresh()
End Sub```

Because VB .NET doesn't provide a simple relative line drawing method, the code includes one. The DrawRelative subroutine draws a line from the point (m_X, m_Y) to a new point and stores the point's coordinates in the variables m_X and m_Y.

```Private m_X As Integer
Private m_Y As Integer

' Draw the line (m_X, m_Y)-(m_X + dx, m_Y + dy) and
' update m_X = m_X + dx, m_Y = m_Y + dy.
Private Sub DrawRelative(ByVal gr As Graphics, ByVal dx As _
Double, ByVal dy As Double)
gr.DrawLine(Pens.Black, m_X, m_Y, CInt(m_X + dx), _
CInt(m_Y + dy))
m_X = CInt(m_X + dx)
m_Y = CInt(m_Y + dy)
End Sub```

Check the program's Refresh box to make it update its display as it draws each line. This slows the program down greatly but lets you see the order in which the routine draws its lines.

For more information on fractals, see my book Visual Basic Graphics Programming.  Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.  Updated 