BLOG.CSHARPHELPER.COM: Draw a Barnsley fern fractal in C#
Draw a Barnsley fern fractal in C#
For information about this fractal, see Barnsley's Fern by Eric W. Weisstein from MathWorld, a Wolfram Web Resource.
The program starts from a random point. At each step, it randomly picks a function (with non-uniform probability) and applies the function to the point to find the next point. It then plots that point.
Each function has the form:
X(n+1) = A * X(n) + B * Y(n) + C Y(n+1) = D * X(n) + E * Y(n) + F
The Form_Load event handler initializes the parameters for each function in the m_Func array and the probability for each function. It also sets the color to be used when plotting a point found by each function. Using different colors is interesting and gives you some sense of what each set of functions does but the final result here is drawn in green.
private float[] m_Prob = new float[4]; private float[,,] m_Func = new float[4, 2, 2]; private float[,] m_Plus = new float[4, 2]; private Color[] m_Clr = new Color[4];
// New colors to make a lime fern. m_Clr[0] = Color.Lime; m_Clr[1] = Color.Lime; m_Clr[2] = Color.Lime; m_Clr[3] = Color.Lime;
MakeFern(); }
The MakeFern subroutine draws the fractal into the Bitmap named m_Bm. The form's Paint event handler simply displays the Bitmap.
Subroutine MakeFern starts at point (1, 1) and repeatedly applies randomly selected functions, plotting each point on the Bitmap.
private void MakeFern() { Bitmap bm = new Bitmap(picCanvas.ClientSize.Width, picCanvas.ClientSize.Height); using (Graphics gr = Graphics.FromImage(bm)) { gr.Clear(picCanvas.BackColor);
Random rnd = new Random(); Color clr = Color.Red; int func_num = 0, ix, iy; float x = 1, y = 1, x1, y1; for (int i = 1; i <= 100000; i++) { double num = rnd.NextDouble(); for (int j = 0; j <= 3; j++) { num = num - m_Prob[j]; if (num <= 0) { func_num = j; clr = m_Clr[j]; break; } }
x1 = x * m_Func[func_num, 0, 0] + y * m_Func[func_num, 0, 1] + m_Plus[func_num, 0]; y1 = x * m_Func[func_num, 1, 0] + y * m_Func[func_num, 1, 1] + m_Plus[func_num, 1]; x = x1; y = y1;
Comments