Page 2 of 2
Trying it out
That’s it and yes it does draw a tree. If you want to try it put a button on the form and add:
DrawBranch( 300, 400, 75, 0.9, 90 , 30 , 8);
This draws a tree with 8 branches getting shorter by 0.9 each time and rotating through 30 degrees to the left and right.
A depth 8 tree
Changing the parameters changes the look of the tree. For example, to produce a more “Mediterranean” tree try:
DrawBranch( 300, 500, 75, 0.9, 90 , 15 ,10);
Just changing the angle increment produces different shapes
To see a forest all we need to do is generate some random trees. If we also want the trees to be in a random color we need to change the function to accept a color parameter and make use of it in the Line drawing command:
private void DrawBranch( double x, double y, double L, double s, double t, double dt, int d, Color c) double x1 = x + L * Math.Cos(t * Math.PI / 180); double y1 = y  L * Math.Sin(t * Math.PI / 180); canvas1.Children.Add( new Line() {X1=x,Y1=y,X2=x1,Y2=y1, Stroke=new SolidColorBrush(c), StrokeThickness=2}); if( d > 1) { DrawBranch(x1, y1, L * s, s, t + dt, dt, d  1,c); DrawBranch(x1, y1, L * s, s, t  dt, dt, d  1,c); } }
Now we can set the parameters using a random number generator:
Random R = new Random(); double x = 50+500 * R.NextDouble(); double y = 50 + 500 * R.NextDouble(); int d = R.Next(5, 10); double L = y/ R.Next(5,10); double dt = R.Next(15, 35); Color c = Color.FromRgb( (byte)R.Next(0, 255), (byte)R.Next(0, 255), (byte)R.Next(0, 255)); DrawBranch( x, y, L, 0.8, 90 , dt ,10,c);
A forest of recursive trees
Once you get the idea of drawing recursively you can generalise the idea and introduce additional commands that make the tree more realistic. Try limiting the spread of the outer branches to make the tree grow up. Try making the branches curved. Try inventing a different branching mechanism. It’s not difficult and it's very effective. Who needs fractals!?
To access the code for this project, once you have registered, click on CodeBin.
More projects
Getting started with Windows 7 Gadgets
Given the very real possibility that Windows 8 will have an HTML5/JavaScript framework and an app store, now is a very good time to look at the existing support for these technologies in the form of S [ ... ]

Automatic Web Page Use With .NET
Using web browser macros, the need to get more control over what is happening during the automated use of a web page becomes increasingly obvious. After trying a number of possible solutions, C# and . [ ... ]
 Other Projects 
<ASIN:1430272058>
<ASIN:1556229119>
<ASIN:1849960224>
<ASIN:1430226501>
