Recipe 10.5. Creating an Animation Using Multiple Images


Problem

You want to add a simple animation to your application without resorting to complicated video techniques.

Solution

Sample code folder: Chapter 10\ ImageListAnim

There are several ways to create simple animations in your Visual Basic 2005 applications, and the next three recipes will show you three different ways to do so. One straightforward and effective technique is to store bitmap images in an ImageList control, and then display them sequentially in a PictureBox with each tick of a timer.

Discussion

An ImageList control holds multiple images in one spot in your application to use with other controls that require multiple images. For example, the ListView, TreeView, Toolbar, and other controls all work hand in hand with an ImageList to display customized images on their surfaces. But you can use an ImageList for other purposes, too, as this recipe shows.

The first step in creating an animation is to create or collect a sequence of images to be displayed. Figure 10-4 displays a collection of wind-tower bitmaps with the turbine blades in rotated positions slightly shifted from one to the next.

Figure 10-4. A series of nearly identical images can be used to create a smooth-running animation


In the sample application for this recipe, an ImageList has been added to the main form, and its Images collection has been filled with the windmill images (in a specific order). Figure 10-5 shows the image collection.

To display these images sequentially as an animation, add a PictureBox and a Timer control to the form:

 Private Sub Timer1_Tick(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles Timer1.Tick    ' ----- Draw the next image on each tick.    Static imageNumber As Integer    imageNumber = (imageNumber + 1) Mod ImageList1.Images.Count    PictureBox1.Image = ImageList1.Images(imageNumber) End Sub 

The timer should be enabled, and its Interval property should be set to a number of milliseconds appropriate for the animation. In this case, 40 milliseconds worked well.

As soon as the form loads, the action starts. With each tick of the timer, the static variable imageNumber increments to point to the next image in the ImageList control. The image is loaded, and the program continues until the Timer's next Tick event. Figure 10-6 shows one frame of the animation.

Figure 10-5. Adding images to an ImageList control


Figure 10-6. Displaying images sequentially in a PictureBox to create an animation





Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net