You are on page 1of 11

Graphics and Animation in Visual Basic

Written by Mike James


Article Index
Graphics and Animation in Visual Basic
Bouncing and spinning
Flashing animation
Page 1 of 3

Visual Basic makes it very easy to load and display images that have been prepared earlier and
stored on disk or on a web server. Not only does VB make this easy, with the addition of the
Timer control making things move is very easy indeed.

In this chapter of the eBook Master Visual Basic 2010, we look at how to display an image,
animate an object and meet the idea of objects that don't necessarily have a visual representation,
i.e. objects that are not controls.

Step One - The PictureBox


The PictureBox is a full control which has all the properties that you have encountered but it is
special in that it can be used to display an image. To try it out start a new VB Windows Forms
project and drag-and-drop a PictureBox onto the form. The PictureBox has a range of standard
properties and methods and some that allow you to load an graphics file and control how it is
displayed. The most important of these you can work with by clicking on the small arrow icon in
the top right.

As a general tip you should always lookout for the small arrow icon to work with the standard
tasks needed to customise a control. In this case you can achieve the same results working with
the Properties window or writing code but for some controls a Wizard is provided which makes
things much easier.
Step Two - The Image Property
The most important property of either type of control is its Image property which specifies the
graphics file that will be displayed.You can display a file in GIF, BMP, JPEG, PNG or TIFF
format. The list can be extended by loading custom decoders but this is usually enough.

Setting the bitmap to display a file can be done using properties or in code. The most difficult
part of the task is ensuring that the file you want to display is in the location you specify or if
you want to put it the other way round ensuring that the location you specify really is where the
file is stored.

In the example program a PNG file called Off.png is stored in the project directory in Debug i.e.
in

project\bin\debug

The image file is included in the download stored in the CodeBin - see later.

If you now click on the right arrow or try to set the Image property in the Properties window the
Select Resource dialog box appears. This lets you specify two different way of working with
files. You can select Project resource file or you can select Local resource. The difference is that
if you select Project resource file the image file is copied into the project and it gets distributed
with the application automatically. If you select Local resource then the file is left where you put
it and it is just used by the program. Of course this means that if you distribute the program to
other people you have to make sure that you include a copy of the file and make sure it is stored
in the correct location.

Of the two Project resource file is often the better choice, but for simplicity and generality we
will use Local resource in this example. So select Local resource. click Import and navigate to
the file you want to load into the PictureBox. When you click OK you will be able to see the
image in displayed by the PictureBox.

Step Three - Controlling the image


There are a small number of properties that you can set to control how the image is displayed in
the PictureBox. The most important is the Size Mode property.

If you set this to Normal then the image will be displayed in the PictureBox at its correct size. If
the picture box is too small then you only see what fits into the display area and it is too big the
image is surrounded by a Background fill .

If you set this to StretchImage the graphic is scaled so that it fills the current size of the
PictureBox.

Zoom works in the same way as StretchImage but the scaling doesn't distort the image i.e. it
keeps the aspect ratio fixed. Of course this means that the image might not fill the PictureBox in
one dimension.

If you set this to AutoSize then it is the PictureBox which changes its size to always fit the size
of the image being displayed.

CenterImage works like Normal but the image is centered rather than being in the top left hand
corner.

Step Four - Moving pictures


There are many uses for a PictureBox control. You can just use it to display a photograph on a
form say but one of the most common is to create an animation effect.

This can be done in one of two ways.

The first is that you can actually move the graphic by changing its Top and Left properties while
the program is running.

The Top and Left properties are applied to all controls and specify the position of the top left
hand corner. By changing them as the program runs you can make a control appear to move.

For example, if you place an Image control called PictureBox on a form along with a button
called Button1 then you can define the button's click routine to be:

Private Sub Button1_Click(


ByVal sender As System.Object,
ByVal e As System.EventArgs)
Handles Button1.Click
PictureBox1.Top = PictureBox1.Top + 10
PictureBox1.Left = PictureBox1.Left + 10
End Sub

This will make PictureBox1 move 10 units diagonally each time the button is clicked.

You can use the same technique to move any control.

To achieve free movement however, i.e. movement that doesn't depend on clicking a button, you
also need to know about the Timer control.

The only problem with using Top and Left in this way is that the control is redrawn after each
change. This means that it actually moves horizontally and then vertically in a sort of steppy
fashion rather than along a smooth diagonal. To make a control move smoothly it is better to use
the SetBounds method.

We haven't really discussed methods as yet but you can think of them as additional commands
that apply directly to objects. For example, to move a control called Image1 to a new location
and change its size you would use

PictureBox1.SetBounds(x, y,w,h)

where x and y are the new settings of Left and Top respectively and w and h specify the new
width and height.

Of course the problem here is that if you only want to move the control you have to still specify
its width and height. There are a number of ways around this problem that work in general but
for the PictureBox control we can use a simple trick that means that w and h are ignored. If you
set the PictureBox to AutoSize then it doesn't matter what size you set it to be it will ignore your
specification and resize itself to fit the image being displayed.

So using SetBounds and assuming that Size Mode is set to AutoSize the previous example
becomes:

Private Sub Button1_Click(


ByVal sender As System.Object,
ByVal e As System.EventArgs)
Handles Button1.Click
PictureBox1.SetBounds(
PictureBox1.Left + 10,
PictureBox1.Top + 10, 0, 0)
End Sub

Notice the use of Left and Top within the Move method. This simply makes the control move 10
units diagonally from where it currently is positioned. Also notice that the only reason that
setting the size of the control to zero is that it auto-resizes each time to fit the image.

Prev - Next >>


Graphics and Animation in Visual Basic
Written by Mike James
Article Index
Graphics and Animation in Visual Basic
Bouncing and spinning
Flashing animation
Page 2 of 3

Step Five - Loading pictures


The second way of animating something is to change the graphic being displayed in the
PictureBox. By showing images that show something in slightly different positions then you can
create the illusion of movement.

You might think that this was just a matter of setting the Image property to the correct file but a
graphics file has to be loaded into memory before it can be displayed. When you set the Image
property Visual Basic actually does quite a lot of work behind the scenes.

The point is that what you specify as the image is a string of characters that gives the location of
the file. The Visual Basic system finds the file and loads it into the machine's memory ready to
display in the PictureBox. When you set the PictureBox's Image property in code you have to do
this job for yourself.

The key idea here is that an image is loaded into memory as an Image object. This is just like all
of the objects you have met so far and comes complete with properties and methods that you can
make use of. The big difference is that this object only exists in code. You can't see it on the
form and it isn't in the Toolbox. It is an object without a visible component.

Every VB program has a standard Image object that you can use to load a file. Later you will
discover that there are ways to create additional Image objects. The built in or "static" Image
object has a method called FromFile that will load a graphics file and create an new Image
object.

So for example to load a file as an Image into a PictureBox you would use:

PictureBox1.Image=Image.FromFile("filename")

where, of course, you would replace filename by the name of the graphics file.

For example, if there are two buttons on a form called Button1 and Button2 and an PictureBox
control called PictureBox1 then you can make a light go on and off by defining the click
routines as:

Private Sub Button1_Click(


ByVal sender As System.Object,
ByVal e As System.EventArgs)
Handles Button1.Click
PictureBox1.Image =
Image.FromFile("Off.png")
End Sub

Private Sub Button2_Click(


ByVal sender As System.Object,
ByVal e As System.EventArgs)
Handles Button2.Click
PictureBox1.Image =
Image.FromFile("On.png")
End Sub

To set an Image or Picture Box to a blank simply specify:

PictureBox1.Image=nothing

Step Six - The Timer Object


Now that you have met an object that doesn't make any sort of appearance on the Form it is time
to meet an object that appears on the Form when you are designing it but not when you run the
program - i.e. the Timer control. A Timer simply generates events at regular intervals and the
idea is that it is easy to put a Timer on a form and customise it using the Properties Window but
when the program runs nothing needs to be seen - the timer just ticks.

Although the Timer object has lots of different uses you really can't mention the idea of
animation without it. When you place a Timer on a form you don't see anything when you run
the program - it is an entirely invisible control. What it does is to create events at regular
intervals. These events are handled by the Timer's Tick event handler - this is the only event that
a Timer responds to.

In other words, you can use a Timer object to ensure that something happens at a regular
interval. Not surprisingly this interval can be set via the Interval property. Less obviously, the
interval is specified in milliseconds - and one millisecond is one thousandth of a second, i.e.
1000 milliseconds equal one second. You can also switch a Timer on and off using its Enabled
property . When this is true the Timer causes events at the specified interval and when it is false
the Timer does not operate.

When you first encounter the idea of a timer it seems like the answer to nearly everything you
want to do and this does result in a tendency to use lots of Timer objects.If you have a lot of
different things to do at different times then the beginner tends to create a timer for each interval.
The result is generally a mess that is difficult to understand and hence debug or modify.

A much better method is to use only one Timer object and set it to "tick" at the smallest time
interval you want to use. Then create a "tick" handler which counts the ticks to work out what to
do at any given time.

For example, to show one image at one second and another at two seconds and so on you might
use a Timer. Place a Timer on the form and set its Interval to 1000, and Enabled to True. The
event handler (which you can create automatically by double clicking on the Timer) is something
like:

Private Sub Timer1_Tick(


ByVal sender As System.Object,
ByVal e As System.EventArgs)
Handles Timer1.Tick
Static count
count = (count + 1) Mod 2
If count = 1 Then
PictureBox1.Image =
Image.FromFile("Off.png")
Else
PictureBox1.Image =
Image.FromFile("On.png")
End If
End Sub

There are various things in this example that are subtle but you should be able to follow the
general idea. There are also some technical things. For example the variable count has to be
defined as Static so that it keeps its value between ticks.

The statement count=(count+1) Mod 2 count the ticks but using modulo 2 i.e. it counts 0, 1, 0, 1,
0,1 and so on. (In general counting Mod N goes 0,1,2,...N-1, 0, 1,2 .. and so on i.e. count up to
one less than N and then start at 0 again.)

Using this the IF statement tests to see which picture should be loads. The result is an animation
of something flashing.

<< Prev - Next >>


Graphics and Animation in Visual Basic

Written by Mike James

Article Index

Graphics and Animation in Visual Basic

Bouncing and spinning

Flashing animation

Page 3 of 3

Bouncing and spinning

This example is a very simple animation - it just bounces a spinning ball around the screen. This
is quite an ambitious program and it introduces some new ideas, techniques and Visual Basic
instructions.
Obviously the movement is going to be created by a timer which updates the position of the
"ball" every so many milliseconds. So the first thing to do is place a Timer on the form, set
Interval to 100 and Enabled to true.

Two variables are needed - vx and vy - to store the horizontal and vertical velocities respectively
and these need to be declared as properties:

Dim vx, vy As Integer


To initialise these to a suitable starting velocity we need to use the FormLoad event which you
can guess occurs everytime the Form is loaded:

Private Sub Form1_Load(


ByVal sender As System.Object,
ByVal e As System.EventArgs)
Handles MyBase.Load
vx = 10
vy = 10
End Sub
Obviously the values that you use will alter how fast the ball moves but notice that vx and vy are
the distance the ball moves for each tick of the timer. Next we need to define the tick event
handler for the timer. The image of the ball is going to be loaded into Picture1.

To create the rotation effect we have three ball images each rotated by 90 degrees:

The idea is that the Tick event handler will load each image in turn and we will use a counter to
work out which one to load.

Private Sub Timer1_Tick(


ByVal sender As System.Object,
ByVal e As System.EventArgs)
Handles Timer1.Tick
Static count
PictureBox1.SetBounds(
PictureBox1.Left + vx,
PictureBox1.Top + vy, 0, 0)
If (PictureBox1.Top + PictureBox1.Height)
> Height Then vy = -vy
If PictureBox1.Top < 0 Then vy = -vy
If (PictureBox1.Left + PictureBox1.Width)
> Width Then vx = -vx
If PictureBox1.Left < 0 Then vx = -vx
count = (count + 1) Mod 3
Select Case count
Case 0
PictureBox1.Image =
Image.FromFile("Ball1.png")
Case 1
PictureBox1.Image =
Image.FromFile("Ball2.png")
Case 2
PictureBox1.Image =
Image.FromFile("Ball3.png")
End Select
End Sub

The first instruction moves the ball by adding the velocities to its current position. The four IF
statements at the start test for the ball going out of the Form. If it does go out of Forms area then
its velocity in the appropriate direction is reversed - i.e. if it goes out of the left or right hand side
the horizontal velocity is reversed. This is a standard way of creating a bouncing ball.

After this the counter is incremented modulo 3 and tested for which of the possible three ticks
we have reached.The counter counts in the sequence 0,1,2,0,1,2,0 and so on. The Select
statement is new but you can see the general idea is that it selects which instuction to carry out
depending on the value of counter.

Each tick loads a different graphics file. That's all there is to it and the ball will rotate and
bounce around the screen for ever!

This is a simple demonstration of animation and how objects like Timers and PictureBoxes work
together to create such effects. It most certainly isn't a perfect program. In paraticular it loads the
graphics files each and every time they are used! This slows things down and is very ineffiecent.
A better program would load the graphics files just once, probably in the Form Load event
handler and then use them as needed.

As you can see there is a lot more to learn!

To access the complete project including the graphics once you have registered, click on
CodeBin.
This is the fifth chapter of the ebook Master Visual Basic 2010.

See also:
Chapter 1 - Hello VB

Chapter 2 - Mastering VB Properties

Chapter 3 - Mastering VB Events

Chapter 4 - Mastering VB Controls

If you would like to be informed about new articles on I Programmer you can either follow us on
Twitter, on Facebook , on Digg or you can subscribe to our weekly newsletter.

You might also like