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.

 

tree1

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);

tree2

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);
tree3

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


.NET MP3

Running the LAME MP3 encoder under the control of .NET isn't difficult and it provides a really good example of controlling an external .EXE.



Reading A BMP File In JavaScript

Reading in a graphics file that HTML doesn't support is fairly easy using JavaScript's new typed array feature. In this project we read, decode and display a BMP file. 


Other Projects

<ASIN:1430272058>

<ASIN:1556229119>

<ASIN:1849960224>

<ASIN:1430226501>



Last Updated ( Monday, 28 June 2010 )
 
 

   
RSS feed of all content
I Programmer - full contents
Copyright © 2014 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.