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


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);
new Line()
Stroke=new SolidColorBrush(c),
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

Accessing Salesforce Data from Angular.js

In this tutorial we show you how to sign up for a Salseforce developer account and build a connected app that gets contacts from the user’s Force.com account and shows them using twitter bootstrap.

 [ ... ]

The Minimum Spanning Tree - Prim's Algorithm

Finding the minimum spanning tree is one of the fundamental algorithms and it is important in computer science and practical programming. We take a look at the theory and the practice. 

Other Projects





Last Updated ( Monday, 28 June 2010 )

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