Using CPictureGlass


Let’s check out the client code in FUN.FRM (project FUNNGAME.VBP) before we talk about the implementation. The CPictureGlass declaration is at the module level so that it can be accessed from various routines:

Private pgPicture As New CPictureGlass

Although the pgPicture variable is declared at the form level, the New keyword in the declaration means that the object isn’t actually created until the first reference. That first reference had better be the Create method, since the object is meaningless without initialization. In the Fun ’n Games program, object creation and initialization occurs in the cmdAnimate_Click sub:

Private Sub cmdAnimate_Click()
If cmdAnimate.Caption = “&Animate Picture” Then
With pgPicture
‘ Draw picture on center of form with white background
.Create Me, imgAniBmp.Picture, clrMask, Width / 2, Height / 2
‘ Constant controls pace, sign controls direction
xInc = .Width * 0.05
yInc = -.Height * 0.05
End With
SetTimer eatPicture
cmdAnimate.Caption = “Stop &Animate”
Else
SetTimer eatNone
cmdAnimate.Caption = “&Animate Picture”
End If
End Sub

This sub is a toggle that turns animation on or off. After calling the Create method, you can use CPictureGlass properties such as Visible, Left, Top, Width, and Height.


The SetTimer sub tells the Timer control to handle the animation. (The Fun ’n Games program also uses the same Timer control to animate card backs.) We’re not interested yet in the details of how SetTimer tells the timer which events to handle. All that matters is that the timer event calls AnimatePicture. The code is listed below:

Private Sub AnimatePicture()
With pgPicture
If .Left + .Width > ScaleWidth Then xInc = -xInc
If .Left <= Abs(xInc) Then xInc = -xInc
If .Top + .Height > ScaleHeight Then yInc = -yInc
If .Top <= Abs(yInc) Then yInc = -yInc
.Move .Left + xInc, .Top + yInc
End With
End Sub

This code simply moves the picture around the form, bouncing back in the other direction when it hits a border. Not very difficult. The hard part is inside.


The Fun ‘n Games program takes shortcuts. It sets AutoRedraw to False because otherwise some of the dynamic effects wouldn’t work or would be too slow. AutoRedraw works by maintaining
a behind-the-scenes bitmap that represents the form surface. When you use PaintPicture with AutoRedraw, you’re drawing to this bitmap instead of to the real form surface. That might work for some programs, but it’s not fun and games. If you don’t let Visual Basic redraw automatically, you’re supposed to redraw yourself in the Paint event. That wouldn’t be much fun either because you’d have to remember everything you drew and redraw it whenever the window moved or was obscured by another application. Fortunately, we sample programmers can ignore such inconveniences, leaving the toughest parts of animation to real programmers like you.