VB.NET – Drawing Shape Objects

This post was written by Brandon on December 9, 2008
Posted Under: Visual Basics .NET

Since I learned this, I have been able to do a lot with handling objects. I will show how to be able to draw as many shape objects (in this case Rectangles) on the form and be able to handle them all, including collisions and movement!
Note: This was made in Visual Studio 2008, if you try on previous versions you may have problems! You can download Visual Studio 2008 for FREE on Microsoft's website!

The first few declarations for the top of your VB.NET project should be

Dim myGraphics As Graphics
Dim myRectangle(500) As Rectangle
Dim myPen As New Pen(Color.Red)
Dim myBrush As New SolidBrush(Color:=Color.Red)

myGraphics declares what you need to be able to draw any type of graphic to the form
myRectangle(500) declares an array of 500 rectangles. This means we can draw up to 500 rectangles, then clear them all and reuse them. This can be changed to any number. Using an ArrayList allows as many as you want to be added, this will be covered in a week or two as I have it written in Java.
myPen is declared as a pen and the color Red, this is the outline of the shape drawn
myBrush is declared as a brush and the color Red, this is the fill color of the shape drawn.

For example, if myPen is blue and myBrush is red and a rectangle is drawn, the rectangle will have a blue outline and a red inner filling.

Next is a simple method used to draw the specific rectangle in the array, at a set X and Y position:

Sub drawRectangle(ByVal rectanglenum As Integer, ByVal xpos As Integer, ByVal ypos As Integer)
myGraphics = Graphics.FromHwnd(ActiveForm().Handle)
myRectangle(rectanglenum) = New Rectangle(x:=xpos, y:=ypos, Width:=20, Height:=20)
myGraphics.DrawRectangle(pen:=myPen, rect:=myRectangle(rectanglenum))
myGraphics.FillRectangle(brush:=myBrush, rect:=myRectangle(rectanglenum))
End Sub

The width and height are preset within the sub. All the programs I use this in uses shapes that do not require a different size for each. As you can see, it takes the rectanglenum to draw and uses myGraphics to draw and fill that specific rectangle within the array.

Here is an example to draw 500 rectangles randomly within your form:
First you need a simple function to generate random numbers, use this one:

Function Random(ByVal Lowerbound As Long, ByVal Upperbound As Long)
Randomize()
Random = Int(Rnd() * Upperbound) + Lowerbound
End Function

Then, within a button or form load, or where ever else you want to create the shapes, do something like this:

For i As Integer = 1 To 500 Step 1
drawRectangle(i,Random(1, Me.Width - 100),Random(1, Me.Height - 100)
Next

And there you are, 500 randomly placed squares!

In a next post, I will show handling movement and collisions!!

Reader Comments

Trackbacks

Add a Comment

required, use real name
required, will not be published
optional, your blog address

Next Post: