Drawing trees
Written by Ian Elliot
Monday, 05 April 2010
Article Index
Drawing trees
Forest

## 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

 The Knapsack ProblemI like problems that look simple and turn out to be really difficult. It's the way that something simple can hide a complexity that you never guessed at. Fortunately for me the universe seems to be bu [ ... ] + Full Project Getting To Know WPFWPF was, and is, Microsoft's second generation UI framework. It went through a period where its future was uncertain, but now it's back and part of .NET Core. What could be a better time to get starte [ ... ] + Full Project Other Projects

<ASIN:1430272058>

<ASIN:1556229119>

<ASIN:1849960224>

<ASIN:1430226501>

Last Updated ( Monday, 28 June 2010 )