Draw a curlicue fractal in C#

example

For information about how this fractal works, see Curlicue Fractal by Eric W. Weisstein from MathWorld, a Wolfram Web Resource.

The program starts by drawing a line segment in the direction of the X axis. It then iteratively calculates theta and phi using these equations:

theta(n + 1) = (theta(n) + 2 × Pi × S) mod (2 × Pi)
phi(n + 1) = (theta(n) + phi(n)) mod (2 × Pi)

For some irrational number S. At each step, the program draws a new line segment in the direction given by phi.

The following DrawCurlicue method draws 10,000 segments following these rules.

// Draw the curve.
private void DrawCurlicue(Graphics gr)
{
    const int scale = 2;
    gr.ScaleTransform(
        scale,
        scale,
        MatrixOrder.Append);
    gr.TranslateTransform(
        picCanvas.ClientSize.Width / 2,
        picCanvas.ClientSize.Width / 2,
        MatrixOrder.Append);

    double s = double.Parse(txtS.Text);
    double theta, phi, x0, y0, x1, y1;
    theta = 0;
    phi = 0;
    x0 = 0;
    y0 = 0;

    // Use a zero-width pen so it draws as thin as possible
    // even after scaling.
    using (Pen thin_pen = new Pen(Color.Red, 0))
    {
        for (int i = 1; i <= 10000; i++)
        {
            x1 = x0 + Math.Cos(phi);
            y1 = y0 + Math.Sin(phi);
            gr.DrawLine(thin_pen, (float)x0, (float)-y0,
                (float)x1, (float)-y1);
            x0 = x1;
            y0 = y1;

            phi = (theta + phi) % (2 * Math.PI);
            theta = (theta + 2 * Math.PI * s) % (2 * Math.PI);
        }
    }
}


Download Example   Follow me on Twitter   RSS feed


This entry was posted in algorithms, drawing, fractals, graphics, mathematics and tagged , , , , , , , , , , . Bookmark the permalink.

One Response to Draw a curlicue fractal in C#

  1. I have been working with the C# platform for a long time. it was really interesting to go through the code that can do such a great job. I appreciate the brilliance behind this code. I am excited to try this out. Keep posting. Thanks for sharing.

Leave a Reply

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