Draw a skewed Sierpinski gasket with any number of corners in C#

One way to draw a Sierpinski gasket is to start with 3 corners. To generate a point, randomly pick a corner and move halfway between the current position and the selected corner. See Draw a Sierpinski gasket in C# for more information.

This example lets you pick corners at run time. Left-click on the form to pick at least 2 points. Then right-click to start the program running. The program uses the following code to draw the modified gasket.

// Draw 1,000 points.
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 - RADIUS, pt.Y - RADIUS, 2 * RADIUS, 2 * RADIUS);
gr.DrawEllipse(Pens.Blue, pt.X - RADIUS, pt.Y - RADIUS, 2 * RADIUS, 2 * RADIUS);
}

// Draw 1000 points.
for (int i = 1; i <= 1000; i++)
{
int j = rand.Next(0, Corners.Count);
LastPoint = new Point(
(LastPoint.X + Corners[j].X) / 2,
(LastPoint.Y + Corners[j].Y) / 2);
gr.DrawLine(Pens.Blue, LastPoint.X, LastPoint.Y,
LastPoint.X + 1, LastPoint.Y + 1);
}
}
}

For some interesting results, try:

  • Use four corners that make a rectangle.
  • Use a scalene triangle.
  • Use a triangle and add 4 or 5 "corners" in the same spot near the middle.
  • Try other arrangements with duplicate corners.

   

 

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.