Preorder Windows 7 and save 50% or more
 
Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Bookstore...
 
Feedback
Tip Jar
 
XML RSS Feed
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
 
 
TitleDraw a Sierpinski gasket (fractal) in VB.NET
DescriptionThis example shows how to draw a Sierpinski gasket (fractal) in in VB.NET.
KeywordsSierpinski gasket, fractal, random, VB.NET
CategoriesGraphics
 
The program defines three corner points and picks a random corner to use as a starting point. It the repeatedly picks a new random corner and moves halfway from the current point to this corner, and plots the resulting point. When this process repeats enough times, the program draws a Sierpinski gasket.

If you cover and expose the form, the program draws the same Sierpinski gasket.

 
Private LastX As Single
Private LastY As Single

Private CornerX(2) As Single
Private CornerY(2) As Single

' Draw the Sierpinski gasket.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal _
    e As System.EventArgs) Handles MyBase.Load
    Dim i As Integer

    Randomize()
    Me.Show()

    PickPoints()

    Dim gr As Graphics = Me.CreateGraphics()
    Do
        ' Pick the next corner.
        i = CInt(Int(Rnd() * 3))

        ' Move halfway from the current point
        ' to the new corner.
        LastX = (LastX + CornerX(i)) / 2
        LastY = (LastY + CornerY(i)) / 2

        gr.DrawLine(Pens.Red, LastX, LastY, LastX + 1, _
            LastY + 1)

        ' Check for events.
        Application.DoEvents()
    Loop
End Sub

Private Sub Form1_Closing(ByVal sender As Object, ByVal e _
    As System.ComponentModel.CancelEventArgs) Handles _
    MyBase.Closing
    End
End Sub

' Define the corner points.
Private Sub PickPoints()
    Const R As Integer = 5
    Dim i As Integer

    ' Clear.
    Dim gr As Graphics = Me.CreateGraphics()
    gr.Clear(Me.BackColor)

    ' Define the corners.
    CornerX(0) = R + 10
    CornerY(0) = Me.ClientRectangle.Bottom - R - 2
    CornerX(1) = Me.ClientRectangle.Width \ 2
    CornerY(1) = R + 2
    CornerX(2) = Me.ClientRectangle.Right - R - 2
    CornerY(2) = Me.ClientRectangle.Bottom - R - 2

    ' Draw the corners.
    For i = 0 To 2
        gr.DrawEllipse(Pens.Blue, _
            CornerX(i) - R \ 2, CornerY(i) - R \ 2, R, R)
    Next i

    ' Pick a starting point.
    i = CInt(Int(Rnd() * 3))
    LastX = CornerX(i)
    LastY = CornerY(i)
End Sub
 
For more information on drawing fractals and other graphics, see my book Visual Basic Graphics Programming.
 
 
Copyright © 1997-2008 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated