Let’s Get Animated in VB.NET!

This isn’t your rerun of Looney Tunes. Everything and anything that is simulating animation is hot in the world of programming. I guess it is because everyone is trying to mimic that wicked mid air desktop Tom Cruise uses in the movie Minority Report. All animated, all quick and fast, just add some user interaction and we are one step closer to making it reality! The world of animation can get pretty complex and that complexity sometimes discourages the newbie in wanting to try it. That is until they are asked to make an animated icon in their next project at work! While animation can be done in any language, to simplify the process and make it a bit more readable I decided to show you some crude examples in VB.NET. You won’t believe how similar the topics are to the classic cartoon…. in this entry of the Programming Underground!

A little while ago someone on the board asked about animating a simple label to scroll across the form. As most beginners do, when they think animation in .NET they think of timers. For those who don’t know, timers are controls which cause an event (the ‘tick’ event) to fire at regular intervals. You can start and stop timers as well programatically and they are great for launching a whole series of steps or processes. The problem that beginners usually have though is thinking that one timer must trigger another timer or that some how multiple timers have to come into play. This might be the case in real complex animation setups where different objects are running at different time intervals, but for basic control manipulation though, it usually takes just one timer.

So for our first example lets start with the scrolling of a simple label down the form. We will create a new project, place a label (label1), a button (button1) and our timer control (timer1) onto the form. We will then put the label at the top of the form as a starting location. Our button will then trigger the animation event by starting our timer. That is the only thing the button will do here. In the timer’s tick event, we will manipulate that label. The code will look similar to this….

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
		' Lets go with a low number for smoother animation
		Label1.Top = Label1.Top + 3

		Dim bottomValue As Integer = Label1.Top + Label1.Height

		' Check if the bottom of the label has hit the bottom of our form
		' If so, stop the timer.
		If bottomValue >= Me.ClientRectangle.Height Then
			Timer1.Stop()
		End If

End Sub

' Press the button to start the animation
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
		Timer1.Start()
End Sub

In the above code we have two events. One for the timer’s tick event which will fire every so many milliseconds and the button click event for starting our timer. Now notice in the timer event we do a few things. First we manipulate the position of our label by finding the label’s top property value and adding 3 to it. We could make it scroll up by subtracting the value. By adding 3 here it will cause our label to move down three pixels. If we wanted to scroll right or left, we would be adding or subtracting values from the label’s left property.

The second thing it is doing is locating the bottom of the label (or the right side of the label if moving horizontally). We can find this value by adding together the top property of our label with its height. That will give us the y coordinate for the bottom of the label. Since we are scrolling down we need this value to then check against the form’s boundaries to make sure our label doesn’t scroll off form.

The third thing is that we use this new found y coordinate to compare against the form’s “clientRectangle” boundaries. The clientRectangle is the boundaries of a control (our form in this case) which is actually seen by the user and can be used by the user. This is different form the forms height which has things like the toolbar height included in it, causing the overall height of the form to be bigger than what the user can actually see and use. Since we are moving the label down, we want to check the height of this clientRectangle. If we wanted to move left or right we would be checking it against zero or the width of the clientRectangle respectively. Once our label’s bottom edge is greater than or equal to the clientRectangle bottom, we know we are at the end of the form and to stop the timer.

Now to loop this, instead of stopping the timer, we would simply set the label’s top (or left) property back to the original value it started. This will cause it to loop the animation over and over again until we stop the timer.

This next example is going to demonstrate stop frame animation which is the same type of animation used to put cartoons together. Essentially you put together a sequence of images together and show them in order like a flip book. You remember those little stick figure fighting you put on post-it note pads? Same deal here. To do this we need a picturebox (picturebox1) to show the frames, an imagelist (imagelist1) to hold our frames, a timer (timer1) to load the appropriate picture from the image list control to the picturebox, and a button (button1) to then start and stop our timer in essence starting and stopping our animation.

This is how the code looks…

Public Class Form1
	' A form level variable to hold which frame is to show
	' It has to be form level so that our timer1_tick event knows about it from call to call
	Dim imageNumber As Integer = 0

	' Our form load even just sets the picturebox's image to the first one in the list
	Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
		PictureBox1.Image = ImageList1.Images(0)
	End Sub

	' The timer event here picks up the frame from the imagelist control and sets the picturebox
	' It then increments to the next frame in the list.
	Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
		PictureBox1.Image = ImageList1.Images(imageNumber)
		imageNumber = imageNumber + 1

		' If the frame variable is greater than the total images we have in the list 
		' (minus 1 because they are arranged on a zero index system) then we reset the frame count
		If imageNumber > ImageList1.Images.Count - 1 Then
			imageNumber = 0
		End If
	End Sub

	' This simply starts and stops the timer. If the timer is running, stop it, otherwise it is
	' stopped so start it.

	Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
		If Timer1.Enabled Then
			Timer1.Stop()
		Else
			Timer1.Start()
		End If
	End Sub
End Class

As you can see from the comments this is pretty straight forward. Pick up the frames from the image list and put them in the picturebox. Once we reach the limit of our frames, restart back at the first frame (frame 0). Now to control the actual animation speed you can adjust the interval property on our timer. The lower the number, the less amount of time between frames and the faster the animation. I know what you are thinking, create a nice flashing animation to give some seizures. Lets not do that ok? I couldn’t bare the thought that my blog put someone in the hospital.

When you go to load the frames into the imagelist, make sure you add them in order otherwise your animation will be showing the frames out of sequence and it will look like VB.NET is on crack! If you want to create a series of images for yourself, just use a program like ImageReady and save the individual frames. I created about 8 frames and set my timer around 100 milliseconds.

So that is the basics to animation! If you are looking to get into more advanced animation and such, you might want to look into animation libraries out there, something along the video editing line, or you could use custom controls that are all over the Internet. But for basic icon animations, status indicators and such, the above code could work out quite nicely.

Play around with the code I have placed above, add some more stuff to it, submit it for kudos on Dream In Code… I don’t really care. Just don’t give anyone a seizure! 😉

Enjoy!

About The Author

Martyr2 is the founder of the Coders Lexicon and author of the new ebooks "The Programmers Idea Book" and "Diagnosing the Problem" . He has been a programmer for over 20 years. He works for a hot application development company in Vancouver Canada which service some of the biggest tech companies in the world. He has won numerous awards for his mentoring in software development and contributes regularly to several communities around the web. He is an expert in numerous languages including .NET, PHP, C/C++, Java and more.