Draw a Sierpinski fractal curve in C#

The Sierpinski curve is a space-filling curve that is in some ways similar to the Hilbert curve.

The curve is drawn by 4 functions named SierpA, SierpB, SierpC, and SierpD that draw curves across the top, right, bottom, and left sides of the area being drawn.

Each of the functions calls other functions to do the work. For example, SierpA calls itself to draw a horizontal section, draws a line down and to the right, calls SierpB to draw down, draws a horizontal segment, calls SierpD, draws another segment, and finishes by calling SierpA.

The following code shows the SierpA function. If you check the Refresh checkbox, the function refreshes the image on the screen so you can see the curve as it is drawn.

// Draw right across the top.
private void SierpA(Graphics gr, float depth, float dx, float dy, ref float x, ref float y)
{
if (depth > 0)
{
depth--;

SierpA(gr, depth, dx, dy, ref x, ref y);
DrawRel(gr, ref x, ref y, dx, dy);
SierpB(gr, depth, dx, dy, ref x, ref y);
DrawRel(gr, ref x, ref y, 2 * dx, 0);
SierpD(gr, depth, dx, dy, ref x, ref y);
DrawRel(gr, ref x, ref y, dx, -dy);
SierpA(gr, depth, dx, dy, ref x, ref y);
}

if (m_Refresh) picCanvas.Refresh();
}

The Sierpinski function shown in the following code puts the pieces together by calling each of the other functions to draw part of the whole curve.

// Draw a Sierpinski curve.
private void Sierpinski(Graphics gr, int depth, float dx, float dy)
{
float x = 2 * dx;
float y = dy;

SierpA(gr, depth, dx, dy, ref x, ref y);
DrawRel(gr, ref x, ref y, dx, dy);
SierpB(gr, depth, dx, dy, ref x, ref y);
DrawRel(gr, ref x, ref y, -dx, dy);
SierpC(gr, depth, dx, dy, ref x, ref y);
DrawRel(gr, ref x, ref y, -dx, -dy);
SierpD(gr, depth, dx, dy, ref x, ref y);
DrawRel(gr, ref x, ref y, dx, -dy);

picCanvas.Refresh();
}

As a point of interest, note that space-filling curves like this one and the Hilbert curve can give approximate solutions to the Traveling Salesperson Problem (TSP) where the goal is to visit a series of points and return to a starting point while following the shortest possible path. Simply overlay a space-filling curve on the map of the area and visit the points in the order in which the target points are visited by the curve. The result isn't perfect but it's a pretty good start.

   

 

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.