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. It starts with three points shown as circles in the picture. The current point starts at one of the points. Then to generate subsequent points you pick a point at random and move halfway to it from the current position. After you repeat this a bunch of times, the gasket starts to appear.

The example program uses a Timer to draw 1,000 points at a time as shown in the following code. To restart the gasket, resize or hide and restore the form.

// 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);
}
}
}

   

 

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.