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 (DoRefresh) 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 (LastX, LastY) to a new point and stores the point’s coordinates in the variables LastX and LastY.

private float LastX, LastY;
...
// Draw the line (LastX, LastY)-(LastX + dx, LastY + dy) and
// update LastX = LastX + dx, LastY = LastY + dy.
private void DrawRelative(Graphics gr, float dx, float dy)
{
    gr.DrawLine(Pens.Black, LastX, LastY, LastX + dx, LastY + dy);
    LastX = LastX + dx;
    LastY = LastY + 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 it lets you see the order in which the routine draws its lines for depths greater than around 4 or 5.






This entry was posted in algorithms, fractals, graphics and tagged , , , , , , , , , , . Bookmark the permalink.

4 Responses to Draw a Hilbert curve fractal in C#

  1. Pingback: Draw a Sierpinski fractal curve in C# |

  2. Bohdan says:

    very helpfull for me .Thank you.

  3. ABC says:

    I want a code in c++ for hilbert curve in computer graphics, please mail me.

    • RodStephens says:

      Sorry but I don’t do C++ code these days. It should be very similar to the code here.

      The biggest change will be the code that does the actual drawing. You’ll need to figure out how the graphics engine works with your version of C++.

Leave a Reply

Your email address will not be published. Required fields are marked *