Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
 
TitleDraw a fractal binary tree in VB.NET
DescriptionThis example shows how to draw a fractal binary tree in VB.NET.
Keywordsfractal, binary tree, tree
CategoriesGraphics, VB.NET
 
The DrawBranch subroutine draws a branch and then recursively draws two smaller branches from the end of that one.
 
' Recursively draw a binary tree branch.
Private Sub DrawBranch(ByVal gr As Graphics, ByVal depth As _
    Integer, ByVal X As Integer, ByVal Y As Integer, ByVal _
    length As Double, ByVal theta As Double, ByVal _
    length_scale As Double, ByVal dtheta As Double)
    Dim x1 As Integer
    Dim y1 As Integer

    ' See where this branch should end.
    x1 = CInt(X + length * Cos(theta))
    y1 = CInt(Y + length * Sin(theta))
    gr.DrawLine(Pens.Black, X, Y, x1, y1)

    ' If depth > 1, draw the attached branches.
    If depth > 1 Then
        DrawBranch(gr, depth - 1, x1, y1, length * _
            length_scale, theta + dtheta, length_scale, _
            dtheta)
        DrawBranch(gr, depth - 1, x1, y1, length * _
            length_scale, theta - dtheta, length_scale, _
            dtheta)
    End If
End Sub
 
Try adding some randomness to the program. You can change the lengths of branches, their angles, and the number of branches at each point. You can also make each branch somewhat curvy instead of straight. If you tweak the parameters properly, the results can look a lot like real trees.

For more information on fractals, see my book Visual Basic Graphics Programming.

 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated