Title: Draw a Sierpinski gasket in C#
The Sierpinski gasket is a triangle broken into smaller triangles as shown in the picture on the right. There are several ways you can generate this gasket. The one shown here is one of the more surprising.
The program starts with three points (shown as circles in the picture). The "current position" starts at one of the points. To generate subsequent points, the program picks a point at random and moves halfway to it from the current position. After you repeat this a bunch of times, the gasket magically starts to appear.
The example program uses the following code to draw the fractal.
// Add 1000 points to the gasket.
private void tmrDraw_Tick(object sender, EventArgs e)
{
// Draw points.
Random rand = new Random();
using (Graphics gr = this.CreateGraphics())
{
// Draw the corners.
foreach (PointF pt in Corners)
{
gr.FillEllipse(Brushes.White, pt.X - 2, pt.Y - 2, 4, 4);
gr.DrawEllipse(Pens.Blue, pt.X - 2, pt.Y - 2, 4, 4);
}
// Draw 1000 points.
for (int i = 1; i <= 1000; i++)
{
int j = rand.Next(0, 3);
LastPoint = new PointF(
(LastPoint.X + Corners[j].X) / 2,
(LastPoint.Y + Corners[j].Y) / 2);
gr.DrawLine(Pens.Red, LastPoint.X, LastPoint.Y,
LastPoint.X + 1, LastPoint.Y + 1);
}
}
}
Each time the tmrDraw timer ticks, the code plots 1,000 points. The program uses a timer so the program can refresh its drawing. It draws 1,000 points at a time to improve performance.
For each of the 1,000 points, the code picks a random point and moves the variable LastPoint halfway from its current location to the selected point. The code marks the point with a small line (because it's faster than drawing a small circle and easier than plotting individual pixels.)
To restart the gasket, resize or hide and restore the form.
Download the example to experiment with it and to see additional details.
|