Java Reference
In-Depth Information
if (colorValue < 0) {
colorValue = 0;
}
g.setColor(new Color(0, colorValue, 0));
g.drawLine(x1, y1, x2, y2);
int randFactor = rand.nextInt(20) + 10; // a value between 10 and 30
drawSegment(g, x2, y2, angle - randFactor, depth - 1);
randFactor = rand.nextInt(20) + 10; // a value between 10 and 30
drawSegment(g, x2, y2, angle + randFactor, depth - 1);
}
public void paint(Graphics g) {
super.paintComponent(g);
drawSegment(g, getWidth() / 2, getHeight(), -90, 9);
}
}
The algorithm for a fractal tree is quite simple: draw a line; from the end point of that line, draw two
more lines; and so on. I can do that by using fixed values, but I will generate trees that are more realistic
by adding some randomness. To that end, I also changed the color for each part of the tree, using lighter
shades of green towards the top.
In my case, I configured the algorithm from the maximum depth down to 0. For this kind of
algorithm, doing so results in less code (and so should be easier to understand). Since I liked the look of
the tree with a depth of 9, I didn't set the depth value out separately like I did in the
SierpinskiTrianglePanel class. Another interesting feature of this class is that the initial angle is -90. If it
were 0, the tree would grow sideways to the right. This would happen because an angle of 0 draws a line
that lies on the X-axis. Thus, to make the lines go up the Y-axis, I had to rotate 90 degrees to the left (i.e., -
90). An angle of 90 would produce a tree that grew downward (which could be a handy way to model
roots).
The next page shows one result (each result is a bit different) of the FractalTree program.
Search WWH ::




Custom Search