BLOG.CSHARPHELPER.COM: Draw a Sierpinski fractal curve in C#
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--;
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.
Comments