Title: Draw a Sierpinski triangle in C#
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);
}
else
{
// 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 the example to experiment with it and to see additional details.
|