Title: Draw a recursive von Koch snowflake fractal in C#
This example shows how to draw a von Koch snowflake fractal. It uses the same techniques described in the post Draw a recursive snowflake fractal in C#. The DrawSnowflake and DrawSnowflakeEdge methods are exactly the same as before. The only differences are the initiator and generator, which are shown in the second and third pictures above.
The following code shows how the program initializes the von Koch snowflake fractal initiator and generator.
// Coordinates of the points in the initiator.
private List Initiator;
// Angles and distances for the generator.
private float ScaleFactor;
private List GeneratorDTheta;
private void btnGo_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
Application.DoEvents();
// Define an initiator and generator.
Initiator = new List();
float height = Math.Min(
picCanvas.ClientSize.Width,
picCanvas.ClientSize.Height) - 100;
float x1 = (picCanvas.ClientSize.Width - height) / 2;
float x2 = x1 + height;
float y1 = (picCanvas.ClientSize.Height - height) / 2;
float y2 = y1 + height;
Initiator.Add(new PointF(x1, y1));
Initiator.Add(new PointF(x2, y1));
Initiator.Add(new PointF(x2, y2));
Initiator.Add(new PointF(x1, y2));
Initiator.Add(new PointF(x1, y1));
ScaleFactor = (float)(1.0 / Math.Sqrt(5.0));
GeneratorDTheta = new List();
GeneratorDTheta.Add((float)-Math.Atan(1.0 / 2.0));
float pi_over_2 = (float)(Math.PI / 2);
GeneratorDTheta.Add(pi_over_2);
GeneratorDTheta.Add(-pi_over_2);
// Get the parameters.
int depth = int.Parse(txtDepth.Text);
Bitmap bm = new Bitmap(
picCanvas.ClientSize.Width,
picCanvas.ClientSize.Height);
picCanvas.Image = bm;
// Draw the snowflake.
using (Graphics gr = Graphics.FromImage(bm))
{
gr.SmoothingMode = SmoothingMode.AntiAlias;
DrawSnowflake(gr, depth);
}
this.Cursor = Cursors.Default;
}
After declaring the variables, the Go button's Click event handler prepares the initializer and generator. The code calculates the coordinates for the initiator points and saves them. It sets the scale factor to 1/√5 and then saves the generator points.
The code then gets the depth parameter entered by the user, creates a bitmap to hold the snowflake, and calls DrawSnowflake to do the drawing.
Download the example to experiment with it and to see additional details.
|