Draw a Sierpinski triangle in C#

[Sierpinski triangle]

This example shows how to draw a Sierpinski triangle. The post Draw a Sierpinski gasket in C# shows a rather strange iterative way to draw the shape shown in the picture. This example shows another way that is more obviously predictable.

The key is the following DrawTriangle method.

// Draw a triangle between the points.
private void DrawTriangle(Graphics gr, int level,
    PointF top_point, PointF left_point, PointF right_point)
    // See if we should stop.
    if (level == 0)
        // Fill the triangle.
        PointF[] points =
            top_point, right_point, left_point
        gr.FillPolygon(Brushes.Red, points);
        // Find the edge midpoints.
        PointF left_mid = new PointF(
            (top_point.X + left_point.X) / 2f,
            (top_point.Y + left_point.Y) / 2f);
        PointF right_mid = new PointF(
            (top_point.X + right_point.X) / 2f,
            (top_point.Y + right_point.Y) / 2f);
        PointF bottom_mid = new PointF(
            (left_point.X + right_point.X) / 2f,
            (left_point.Y + right_point.Y) / 2f);

        // Recursively draw smaller triangles.
        DrawTriangle(gr, level - 1,
            top_point, left_mid, right_mid);
        DrawTriangle(gr, level - 1,
            left_mid, left_point, bottom_mid);
        DrawTriangle(gr, level - 1,
            right_mid, bottom_mid, right_point);

This method draws a triangle, calling itself recursively to draw smaller triangles if necessary.

The method starts by checking the level parameter. If level is 0, then the method is drawing one of the smallest triangles. In that case, the method simply draws its triangle and stops.

If level is greater than 0, the method finds the midpoints of the edges of its triangle. It then calls itself recursively to fill the three triangles in its corners.

Download Example   Follow me on Twitter   RSS feed   Donate

About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in algorithms, drawing, fractals, graphics, mathematics and tagged , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

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