Draw a Hilbert curve fractal in C#

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 void Hilbert(Graphics gr, int depth, float dx, float dy)
{
if (depth > 1) Hilbert(gr, depth - 1, dy, dx);
DrawRelative(gr, dx, dy);
if (depth > 1) Hilbert(gr, depth - 1, dx, dy);
DrawRelative(gr, dy, dx);
if (depth > 1) Hilbert(gr, depth - 1, dx, dy);
DrawRelative(gr, -dx, -dy);
if (depth > 1) Hilbert(gr, depth - 1, -dy, -dx);

if (m_Refresh) picCanvas.Refresh();
}

Because C# doesn't provide a simple relative line drawing method, the code includes one. The DrawRelative function 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.

// 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 void DrawRelative(Graphics gr, float dx, float dy)
{
gr.DrawLine(Pens.Black, m_X, m_Y, m_X + dx, m_Y + dy);
m_X = m_X + dx;
m_Y = m_Y + dy;
}

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 depth greater than around 4 or 5.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.