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.

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

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.

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

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 theprevious post. Download this example and see that one for more details.