Title: Draw a skewed Sierpinski gasket with any number of corners in C#
The usual way to draw a Sierpinski gasket (as a strange attractor, anyway) 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 details.
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.
Download the example to experiment with it and to see additional details.
|