Recipe 10.7. Creating an Animation by Drawing at Runtime


Problem

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

Solution

Sample code folder: Chapter 10\DrawAnim

A very direct but often effective technique is to simply draw updated images on a graphics surface with each tick of a timer, as shown in this recipe.

Discussion

The following code handles the Tick event for a timer on a form. It redraws the face of the form at each tick. The current position and direction of a block are maintained in form-level variables. The timer's Tick event handler updates those variables so the block drifts around the form and bounces off the walls; the form's Paint event handler is where the actual drawing of the block takes place. At the end of the timer's Tick event handler is a Refresh() command that causes the form to redraw itself. That fires the Paint event, which redraws the block.

Create a new Windows Forms application, and add a Timer control named Timer1. Set its Interval property to 10 and its Enabled property to true. Now add the following code to the form's code template:

 Private UseX As Integer Private UseY As Integer Private MoveX As Integer Private MoveY As Integer Private Const BlockSize As Integer = 50 Private Sub Timer1_Tick(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles Timer1.Tick    ' ----- Draw the next step in the animation.    UseX += MoveX    UseY += MoveY    ' ----- Make adjustments for edge detection.    If (UseX <= 0) Then MoveX = 1    If (UseX >= (Me.ClientSize.Width - BlockSize)) Then _       MoveX = -1    If (UseY <= 0) Then MoveY = 1    If (UseY >= (Me.ClientSize.Height - BlockSize)) Then _       MoveY = -1    ' ----- Redraw the image.    Me.Refresh( ) End Sub   Private Sub Bounce_Paint(ByVal sender As Object, _       ByVal e As System.Windows.Forms.PaintEventArgs) _       Handles Me.Paint    ' ----- Draw the block.    e.Graphics.FillRectangle(Brushes.Red, UseX, UseY, _       BlockSize, BlockSize)    e.Graphics.DrawRectangle(New Pen(Color.Blue, 5), _       UseX, UseY, BlockSize, BlockSize) End Sub 

Two rectangles are drawn, one to create a red square and the other to draw a 5-pixel-wide border around the square. The current values for form-level variables UseX and UseY are used for the position at which to draw the squares. Be sure to set the form's DoubleBuffered property to true for the smoothest effect. Figure 10-9 shows the square block as it drifts towards the walls of the form.

Figure 10-9. The sketched square bounces off the walls smoothly





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