Draw a randomly colored Sierpinski octagon in C#


[Sierpinski octagon]

This example draws a randomly colored Sierpinski octagon. It’s basically the same as the example Draw a randomly colored Sierpinski pentagon in C# except it draws an octagon instead of a pentagon. See that example for most of the details.

There are two main differences between that example and this one. First, the new example uses the following code to set its scale factor.

// Scale factor for moving to smaller octagons.
private float size_scale = (float)(1.0 /
    (2.0 * (1 + Math.Cos(Math.PI / 180 * 45))));

The program adjusts the radius of the smaller octagons by this scale factor to make them fit properly. (This scale needs to change to different kinds of polygons.)

The second change is in the method that generates the points that make up the polygons. The following code shows the new version, which creates an octagon.

// Find the octagon's corners.
private PointF[] GetOctagonPoints(PointF center, float radius)
{
    PointF[] points = new PointF[8];
    double theta = -Math.PI / 2.0;
    double dtheta = 2.0 * Math.PI / 8.0;
    for (int i = 0; i < 8; i++)
    {
        points[i] = new PointF(
            center.X + (float)(radius * Math.Cos(theta)),
            center.Y + (float)(radius * Math.Sin(theta)));
        theta += dtheta;
    }
    return points;
}

This method simply loops the variable theta through the angles at which the octagon’s vertices lie and uses Math.Sin and Math.Cos to calculate the locations of the vertices.

The rest of the program is similar to the previous post. Download this example and see that one for more details.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in algorithms, fractals, graphics, recursion and tagged , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.