Title: 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.
Download the example to experiment with it and to see additional details.
