Hour 18

The Graphic Image Controls

Take a time-out to have some fun! Almost everybody enjoys working with graphics, and Visual Basic's graphic image controls let you add graphics to your applications. The two primary graphic image tools, the Image control and the Picture Box control, work almost exactly alike to add graphic images to your applications. The tools don't give you the ability to draw lines and circles (other controls do that, as you'll see in the next hour), but you can add graphic images to your applications and manipulate those images with what you learn in this hour's lesson.

The highlights of this hour include

The Image Control

The Image control displays graphics on your Form window. The graphics reside in a file, and the Image control determines how that file's graphic image will appear on the screen.

When you add the Image control to your application's form, you will not see an image of any kind, but rather the outline of a rectangle, as shown in Figure 18.1.

Figure 18.1. The Image control does not look like much when you first place it.


TIP: It's been a while (Hour 1, "Visual Basic at Work") since you saw the location of all the Toolbox window's tools. If you cannot locate the Image control or the Picture Box control for this lesson, remember that all of VB's development environment supports tooltips, so you can find the correct controls by hovering your mouse pointer over the tools on the Toolbox window. The Picture Box control icon looks like a desert. The Image control icon contains the sun overlooking mountains.

Preparing the Image

A placed Image control does not look like a graphic image until you set appropriate properties. The most important property setting is the Picture property because the Picture property determines which image appears inside the Image control's boundaries on the form. When you click on the Picture control, Visual Basic displays an ellipsis button you can click to display a Load Picture dialog box that displays a dialog box similar to a File Open dialog box.

The Load Picture dialog box displays a list of files with the graphic-related filename extensions shown in Table 18.1.

Table 18.1. The file types supported by the Image control.
Extension File Description
.bmp A Windows bitmap image file
.cur An animated cursor file (not available for NT programmers at this time because NT does not support animated cursors that move)
.dib An older bitmap image format
.emf An enhanced Windows metafile extension
.gif A Graphic Interchange Format file often used on Web pages
.ico An icon file
.jpg The JPEG image format that stores graphics in a highly compressed format
.wmf A Windows metafile

As long as an image contains one of Table 18.1's filename extensions, you can display that image on your form with the Image control.


NOTE: Visual Basic comes with several supplied graphic image files that take on Table 18.1's formats. These files are stored in VB's Graphics folder and further subdivided into categories and file types. When this lesson discusses using one of these graphic files, search the Graphics folder for the image file to load.

You can select a graphic file that you want to load into the Image control's Picture property, and Visual Basic displays that image on the form. If you were to select the Coins.wmf file located in the Graphics\Metafile\Business folder, you would see the coin metafile appear like the one shown in Figure 18.2. In the figure, the BorderStyle property is set to 1-FixedSingle so you'll know where the Image control edges appear in relation to the image.

Sizing the Image

If the metafile had been smaller, the Image control would have decreased its size to capture exactly the image's measurements. The Image control shrinks or enlarges to display the entire image. Therefore, the typical sizing properties such as Width and Height don't always mean much when you place an Image control on the form. The Image control will adjust to hold the entire image that you want to display there.

Figure 18.2. The Image control enlarges to hold the entire metafile image.


NOTE: You can try this yourself: Place an Image control on the form and load one of the Bitmap folder images into the Image control's Picture property. The Image control shrinks down to the size of a toolbar button to hold the small image.

Once you place an image on the form, you can resize the Image control just as you can other controls by dragging its sizing handles out and in. Therefore, after you load an image such as the Coins.wmf image, you can adjust the sizing handles to make the Image control smaller.


WARNING: When you adjust an image's size after you load a graphic image into the Picture control, the image itself does not really shrink or grow, but the Image control shrinks and grows. If you make the Image control's borders smaller, the control will simply truncate or clip the image that does not fit in the Image control boundaries. Therefore, not all of the image may appear if the control is not large enough. If you expand the Image control again, however, the rest of the image reappears so the truncation occurs only visually, but parts of the image itself are not cut off when you shrink the edges. You can enlarge and shrink the image itself; however, you must use a different property, as you're about to see.

The Image control's resizing capability can also make the Image control a nuisance. For example, other images and controls might be in place and an oversized image would overwrite some of their form area. Therefore, you need a way to control the image's size without clipping the image.

New Term: To clip or to truncate means to hide part of an image with a control's border.

The Stretch property controls the Image control's automatic sizing capabilities. When Stretch is False (the default value), the Image control will expand or shrink to display whatever image you load, but the image inside the Image control does not change but is only clipped as just described. Instead, if you set the Stretch property to True, the image does enlarge or shrink, depending on the size of the Image control. Therefore, if you want to fit an image into a small space, be sure to turn on Stretch before you adjust the Image control's size.

Figure 18.3 shows a form with two Image controls. One is large and one is small, but they both use the same Coins.wmf image you saw earlier. With both controls' Stretch properties set to True, the images themselves grow and shrink inside their boundaries.

Figure 18.3. The images themselves adjust to the Image control borders.

Loading Pictures at Runtime

When your application needs to change the image shown inside an Image control, you cannot simply assign a filename to the Image control's Picture property like this:

imgMyFace.Picture = "C:\Handsome.wmf"  ` Not allowed

The Picture property needs more than a simple assignment. To store a new image in the Image control's Picture property, you must use the LoadPicture() built-in function. Here is the format of LoadPicture():



LoadPicture([strFile])

strFile is a string literal, variable, or control that contains the complete filename and pathname. The graphic image can reside on another computer your application computer is networked to. When the application gets to the LoadPicture() function, the graphic image loads and the picture displays.

Therefore, to load the Handsome.wmf graphic image, you could specify the following line:

imgMyFace.Picture = LoadPicture("C:\Handsome.wmf")  ` Allowed

If you want to change the image's size before the image appears, you can set the image's Visible property to False before loading the picture and adjusting the Height and Width properties. Remember to set the Stretch property to True if you want the image to resize and not be clipped. Once you adjust the size, you then can set Visible to True, and the image will appear in the size you prefer.


TIP: You can remove an image from an Image control by assigning the LoadPicture() function to an Image control's Picture property without specifying a filename argument.

The Picture Box Control

If you applied everything you knew about the Image control to the Picture Box control, you could use the Picture Box control. The Picture Box control works almost exactly like the Image control, with these exceptions:

The Picture Box control automatically clips the image if the image will not fit within the Picture Box control's borders that you set when you placed the Picture Box control.


TIP: You use the Picture Box control to group option buttons into a set just as you can with the Frame control. You then can display a graphic image in the option button background.

Suppose that you placed a rather large Picture Box control on the form but then loaded a graphic file image into the picture box that was much smaller, such as an icon. The Picture Box control would not resize, so the image would appear inside the Picture Box control, such as the one shown in Figure 18.4.

Figure 18.4. The Picture Box control does not always shrink to fit.

The AutoSize property, normally set to False, determines how the Image control responds to a loaded image's size. If AutoSize is False, the control does not resize to fit the image. If, however, you change AutoSize to True, the image control does resize to the image's measurements. If you set AutoSize to True, the image resizes and does not clip. Therefore, the image will always shrink or expand as needed to fit the Image control's size when you set AutoSize to True.


TIP: Once you set AutoSize to True, you can manually adjust the Picture Box control or adjust the control's Height and Width properties in the code. The image will resize along with the picture box's measurements.

Use the Align property to determine where on the form the Picture Box control appears. You can dock the control to any side of the Form window control using the Align property values described in Table 18.2.

Table 18.2. Possible Align property values.
Property Value Description
0-None The Picture Box control appears where you place it in the Form window.
1-Align Top The Picture Box control appears at the top of the Form window.
2-Align Bottom The Picture Box control appears at the bottom of the Form window.
3-Align Left The Picture Box control appears at the left of the Form window.
4-Align Right The Picture Box control appears at the right of the Form window.


TIP: You can use the Picture Box control to create toolbar buttons, so the Align property lets you dock the toolbar buttons to the top of the form. By changing the Align property, your code can move the toolbar elsewhere.

Animating Pictures

You can create animated applications using the Picture Box control by duplicating the same techniques used in the stop-animation techniques that movie-makers use for space and monster battles. This section describes the development of a simple animated Form window. Once you master these simple techniques, more extensive animation might take more time to develop, but the techniques don't change.

Figure 18.5 shows the running animated application. The application simply floats a changing image across the screen. You'll use an Image control and a Timer control to perform the animation.

The Timer control lets your application time the animation. After every time interval that passes (set in the timer's Interval property) the timer's Timer() event procedure executes. The Timer() event procedure can adjust the image's location (and picture if needed). If you adjust the location every half second or so, the animation will appear to move across the form.

New Term: Stop-animation techniques are techniques you use to make an image appear on the screen for a fraction of a second before you put a new image in its place or move the image to a different part of the Form window.

Figure 18.5. The animation application sends an image across the screen.

To build the application, perform these steps:

1. Create a new project and expand the Form window to a Height property of 6840 and a Width property of 5910.

2.
Change the form's Caption property to Animated Cartoon.

3.
Place an Image control on the form. Don't worry about the location or size because you'll adjust those values with code. You'll use an Image control for this application instead of a Picture Box control because the Image control is slightly more efficient and you have no need for the extra properties that come with the Picture Box control.

4.
Select the Face02 graphic image located in your VB\Graphics\Icons\Misc folder. Remember the full path to this file because you'll have to enter this same path a little later in the application's code.

5.
Change the image's Height property to 1685 and the Width property to 1815, and change the image's Name property to imgHappy.

6.
Set the image's Stretch property to True so the happy face resizes like the one in Figure 18.6.

7.
Add a Timer control to the form and name the timer tmrAni. Set the timer's Interval property to 500.

8.
You must now add the code. Double-click the Form window to open the Form_Load() event procedure. Form_Load() will initialize the image's location. Type the following for the Form_Load() event procedure:
Private Sub Form_Load()

  ` Adjust the image's location

  imgHappy.Left = 0   ` Number of twips from

                      ` left of Form window

                      

  imgHappy.Top = 3820 ` Number of twips from

                      ` top of Form window

    

End Sub

Figure 18.6. The happy face is ready for display.

9. Add a Timer() event procedure to the Code window. To add the event procedure, you can click the Code window's Object drop-down list to select the Timer control. The Timer() is the only event procedure possible for a Toolbar control, so Visual Basic opens the Timer() event procedure. You can add code to the event procedure so tmrAni_Timer() looks like this:
Private Sub tmrAni_Timer()

  ` Adjust the Left and Top properties

  ` as well as the happy face shown so

  ` that the face appears to float up

  ` and across the Form window.

  

  ` The first time you declare a Static Boolean

  ` variable, VB initializes it to False

  Static blnFace As Boolean

  

    ` Add to Left and Top only if room is left

  If (imgHappy.Left < 4800) And _

     (imgHappy.Top > 500) Then

       imgHappy.Left = imgHappy.Left + 100

       imgHappy.Top = imgHappy.Top - 50

  Else

    imgHappy.Left = 0    ` Restore image's first

    imgHappy.Top = 3820  ` position.

  End If

  

  ` Change the image displayed

  If blnFace = True Then

     imgHappy.Picture = LoadPicture("C:\Program Files\DevStudio\" & _

                                    "VB\Graphics\Icons\Misc\Face03.ico")

     blnFace = False

  Else

     imgHappy.Picture = LoadPicture("C:\Program Files\DevStudio\" & _

                                    "VB\Graphics\Icons\Misc\Face02.ico")

     blnFace = True

  End If

     

End Sub
Be sure to put the complete pathname for your computer's Face02.ico and Face03.ico files in the Timer() event procedure's LoadPicture() function calls.

10. Save your project and run your application to see the happy face move across and up the screen. The happy face smiles and grins all along the way.

This animation application is simple, but you now have all the tools you need to produce animation effects. You can smooth the animation by displaying images that don't change as rapidly between time intervals as the two happy faces shown here. In addition, if you compile your application, the animation will run more smoothly than if you run the application from within the development environment. (Compile the program by selecting File | Make. Hour 23, "Distributing Your Applications," explains more about application compilation.)

In addition, you can make the image's movement appear slightly less jumpy if you set the image's Visible property to False at the top of the Timer() event procedure and then set the property back to True before leaving the procedure. Hiding the control before adjusting its location properties seems to improve the control's movement. You might not notice a difference, however, if you run the application on a quick computer, especially if you compile the application.

This application uses the Image control for efficiency, but you would probably see little efficiency decrease if you used the Picture Box control instead. Today's computers are fast, and the difference between the controls is not as critical as it once was.

Static Variables

This happy face animation application demonstrates a different variable declaration from the ones you've seen so far. The Static statement declares static variables. Although static variables are local to their procedure, they do not lose their values between procedure calls as regular local variables do. Therefore, if blnFace is True when the tmrAni_Timer() event procedure finishes, the next time Visual Basic executes tmrAni_Timer(), the blnFace variable will still be declared and still be True. Visual Basic only creates and initializes a static variable once per program execution, and the static variable retains its value between procedure calls. The animation application uses the static variable to test which happy face image is showing. If blnFace is True, the event procedure loads the Face03.ico picture into the image and changes blnFace from True to False. On the next event procedure execution, bmlFace will still be False, so the event procedure loads the Face02.ico image and changes bmlFace to True for the next cycle. The static blnFace variable ensures that a different face shows every time interval.

Summary

You probably had some fun working with the graphic image tools shown in this lesson. You now know how to display graphic file images with the Image control and the Picture Box control. Both controls do basically the same task: Both controls display images from graphics files. Their differences lie in the way they display the images when image size becomes an issue; also, the Picture Box control is slightly less efficient but offers more properties, events, and methods.

The next hour further improves your artistic skills. Instead of using prepackaged graphic images, in the next hour you will use Visual Basic's drawing tools to draw your own lines, circles, boxes, and other shapes.

Q&A

Q Can I use graphic images other than the ones that Visual Basic supplies?

A
Certainly. Both the Image control and the Picture Box control load images from any file that uses one of Table 18.1's graphic file formats. As a matter of fact, Visual Basic's images are fairly limited, and most of them are useful for command button pictures and toolbars but very little else.

Q Did you just say command button pictures? When I click the command button's Picture property, no picture appears on the command button, so what's wrong?

A
This is as good a time as any to describe how to put pictures on command buttons. Once you set the command button's Picture property, you must also set the Style property to 1-Graphical. Only a graphical command button can display pictures. The command button works just like before, but now a picture appears. (Erase the Caption property if the caption overwrites the picture's image.) You did not learn about command button pictures in earlier lessons because you were not yet familiar with the LoadPicture() function. You can use LoadPicture() to insert a picture on a command button at runtime if you need to do that. Often, programmers will display a slightly different picture on a command button after the user clicks the button, and you can use LoadPicture() to do the same.

Q If speed is no longer an issue, why should I ever use the Image control?

A
Although the Image control is slightly more efficient, you are correct in remembering that today's computers are generally fast enough to handle both the Picture Box control and the Image control for any application. If, however, you work in a networked environment or if you set up your Windows desktop to run several applications simultaneously, you will want to utilize all resources as efficiently as possible. Therefore, you might prefer to use the Image control to lessen your computer's load if you don't need the Picture Box control's extra properties, events, and methods.

Workshop

The quiz questions and exercises are provided for your further understanding. See Appendix C, "Answers," for answers.

Quiz

1. Which two controls display graphic images?

2.
Which control is more efficient?

3.
What happens if you load a picture into an Image control and the Image control is too small to hold the entire picture (assume default property values)?

4.
What happens if you load a picture into a Picture Box control and the Picture Box control is too small to hold the entire picture (assume default property values)?

5.
What happens if you load a picture into an Image control and the Image control is larger than the picture (assume default property values)?

6.
What happens if you load a picture into a Picture Box control and the Picture Box control is larger than the picture (assume default property values)?

7.
What is wrong with this assignment (assume that the filename and pathname are correct)?
imgFace.Picture = "C:\DataPics\Flower.Ico"
8. Which control helps control animation effects?

9.
True or false: A static variable is a global variable because its value does not change from a procedure's termination to the same procedure's next execution.

10.
When does a static variable first get initialized?

Exercises

1. Add a command button to the animation application so that the animation does not begin until you click the button. The solution to this exercise might not be obvious at first. (Hint: Consider activating the Timer control in the command button's event procedure.) Put a happy face on the command button and hide the command button so it disappears when the application starts animating the happy face.

2.
Change the animation application so that the happy face bounces off all four sides of the Form window.