Hour 24


During this hour you will learn

Shaping Up with Graphics

This lesson introduces you to Visual Basic's fundamental graphics controls and routines. You've already seen how to embed pictures onto your forms with the Image and Picture Box controls. This lesson explains how to draw your own graphic lines, circles, and drawings.

VB programmers use this lesson's line-drawing controls a lot, but generally VB programmers don't use the controls to draw final, complex graphic images. Instead, they often use lines and circles to accent form elements, draw dividing lines, and add shapes to highlight areas of the form. These line-drawing controls are fairly primitive for creating complex graphic images.

FAST TRACK

Do you want more action than simple graphics give? Check out the multimedia topics in Hour 25, "Adding Multimedia to Your Programs".

Topic 1: The Line Control

The Line control supports no events, so its usefulness is limited. Nevertheless, the Line control makes underlining and separating form items easy because it's so simple. Placing lines on a form requires only the placement of the Line control and adjusting its length and thickness.

Overview

The Line control draws lines of any length in any direction on the form. Your VB code can change the Line control's properties, but you'll generally place lines when you design your form and not adjust the lines later at runtime. The control doesn't support a large number of properties, but you'll learn all there is to know about the Line control in this topic. Also, you can't connect two lines together to form a single line-drawn image object. Nevertheless, for underlining and dividing forms, the Line control works well.

Placing Lines on Forms

When you double-click the Line control, Visual Basic places the control in the center of your form (see Figure 24.1). The line has two sizing handles, so you can lengthen or shorten it. Also, you can drag a handle to change the line's orientation so that the line points in a different direction. If you click and hold your mouse button over the line, you can drag the line to a different location.

FIG. 24.1

The line appears at an angle.

Four property values define the line's size and placement: X1, Y1, X2, and Y2. X1 and Y1 specify the line's starting coordinates; X2 and Y2 specify the line's ending coordinates. The coordinates measure in twips. Remember that the 0, 0 coordinate X1, Y1 is the upper-left hand twip position in the Form window.

The Line Control Properties

Table 24.1 describes the most important Line control properties.

Table 24.1 The Line Control Properties

Property

Description

BorderColor

Determines the line's color

BorderStyle

Determines the line's format (see Table 24.2)

BorderWidth

Specifies the line's width; if 1, you can set a BorderStyle value from 1 to 6

X1, Y1, X2, Y2

Determines the line's starting and ending coordinates

As Figure 24.2 shows, the BorderWidth property determines the width of the line, but the width can alter the line's appearance dramatically.

FIG. 24.2

The line widths affect the lines' look.

The BorderStyle property value can range from 0 to 6, as described in Table 24.2. Figure 24.3 shows the various line BorderStyle values.

Table 24.2 The Line Control's BorderStyle Values

Value

Description

0 - Transparent

Background color will show through the line

1 - Solid

Line is solid

2 - Dash

Line is made up of dashes

3 - Dot

Line is made up of dots

4 - Dash-Dot

Line is made up of dashes and dots

5 - Dash-Dot-Dot

Line is made up of dashes and double dots

6 - Inside Solid

Same as 1 - Solid

FIG. 24.3

The BorderStyle property determines the line's style.

BorderStyle property values greater than 1 work only if the line's BorderWidth is greater than 1.

Example

Figure 24.4 shows a caption underlined with the Line control and with separating lines on the form. You can see how the Line control accents form components.

FIG. 24.4

You can use lines and underlining for titles and separation.

Next Step

Figure 24.5 shows that you can use the Line control to draw primitive pictures. You can learn two things from the figure: the Line control isn't flexible for high-resolution graphics, and the author can't draw.

FIG. 24.5

The Line control doesn't produce advanced pictures.

To draw a line, double-click the Line control. Visual Basic places a line in the middle of the Form window. Notice that each end of the line contains a sizing handle. You can extend the line by dragging one of its handles farther away from the center of the line. If you drag a sizing handle up or down the screen, the line points in that direction. You can move the line by dragging the center of the line to any location on the Form window.

Topic 2: The Shape Control

Unlike the Line control, the Shape control draws several shapes, including boxes and circles. The Shape control's properties determine the shape that the Shape control produces. Like the Line control, however, the Shape control doesn't lend itself to a lot of advanced graphic programming. Nevertheless, it can be nice for highlighting certain form components.

Overview

The Shape control's properties determine its many forms. The Shape control is one of the most interesting controls in that its look changes considerably when you modify a single property-Shape.

The Shape's Shapes

Figure 24.6 shows the six shapes you can draw with the Shape control. You can enter the following six values in the Shape control's Shape property to display the shapes:

0 - Rectangle

1 - Square

2 - Oval

3 - Circle

4 - Rounded Rectangle

5 - Rounded Square

FIG. 24.6

The Shape control can display one of six shapes.

The Shape's Properties

The Shape control has other properties in addition to the Shape property. Table 24.3 lists the more important properties.

Table 24.3 The Shape Control's Properties

Property

Description

BackStyle

Determines whether the form background shows through the shape

BorderColor

Specifies the color of the shape's border

BorderStyle

Specifies the form of the line that outlines the shape (see Table 24.2)

BorderWidth

Specifies the shape's border width in twips

FillColor

Specifies the color of the FillStyle pattern

FillStyle

Determines the pattern that fills the shape

Height

The height, in twips, of the highest point in the shape

Width

The width, in twips, of the widest point in the shape

Example

Figure 24.7 shows the fill patterns you can use for your application's shapes. The patterns can greatly affect the way your shapes look.

FIG. 24.7

Set the FillStyle pattern to the interior you need to see.

Next Step

The application described here demonstrates the Shape control and its fill patterns. The application displays a shape on the form and fills the shape with a pattern. You can select a different shape or pattern from the two drop-down lists to change the shape and learn the available patterns better.

Follow these steps to create the application:

  1. Create a new application.
  2. Place a Shape control on the form. Name the shape shpSample. Keep the shape a rectangle.
  3. Adjust the shape's size and location properties to these values: Height: 4,560, Left: 1,710, Top: 720, and Width: 4,560. (You may need to expand the Form window's width to see the whole shape.)
  4. Add a list box named lstShape and assign these properties: Left: 690, Top: 3,840, and Width: 2,130.
  5. Add a label above the list box named lblShape with a Caption property of Shape and assign these properties: FontSize: 18, Left: 1170, Top: 3270, and Width: 1215. Your screen should look something like Figure 24.8.

FIG. 24.8

Your application is shaping up!

  1. Add a list box named lstPattern and assign these properties: Left: 5070, Top: 3840, and Width: 2130.
  2. Add a label above the drop-down list box named lblPattern with a Caption property of Pattern and assign these properties: FontSize: 18, Left: 5505, Top: 3285, and Width: 1215.
  3. You must initialize the two list boxes at runtime. Add the Form_Load() event procedure shown in Listing 24.1.

Listing 24.1 Listshp.bas: Giving Users Entries for the List Boxes

Private Sub Form_Load()

' Initialize the shape drop-down list box

lstShape.AddItem "0 - Rectangle"

lstShape.AddItem "1 - Square"

lstShape.AddItem "2 - Oval"

lstShape.AddItem "3 - Circle"

lstShape.AddItem "4 - Rounded Rectangle"

lstShape.AddItem "5 - Rounded Square"

' Initialize the FillStyle pattern drop-down list box

lstPattern.AddItem "0 - Solid"

lstPattern.AddItem "1 - Transparent"

lstPattern.AddItem "2 - Horizontal Line"

lstPattern.AddItem "3 - Vertical Line"

lstPattern.AddItem "4 - Upward Diagonal"

lstPattern.AddItem "5 - Downward Diagonal"

lstPattern.AddItem "6 - Cross"

lstPattern.AddItem "7 - Diagonal Cross"

End Sub

  1. When users select a value in either drop-down list, you want to update the shape. Therefore, add the two list-box event procedures shown in Listing 24.2.

Listing 24.2 Pattshap.bas: Specifying the Control's Pattern and Shape

Private Sub lstPattern_Click()

' Change the pattern according to the selection

shpSample.FillStyle = lstPattern.ListIndex

End Sub

Private Sub lstShape_Click()

' Change the shape according to the selection

shpSample.Shape = lstShape.ListIndex

End Sub

  1. Add a graceful exit routine by including a File menu Exit option that stops the program's execution. When you run the program, you can see the results of changing the shape's Shape and Pattern properties (see Figure 24.9).

FIG. 24.9

Users can select from shapes and patterns.

Topic 3: A Few Graphic Methods

Visual Basic supports a few graphic methods that are fairly primitive, but they do provide some graphics capabilities that you can display at runtime. Although you could animate the Line and Shape controls that you place on a form by setting and resetting their properties, you may be able to use this topic's graphic methods as better animation tools, especially when you need to set individual screen pixels. (A pixel is another name for picture element and represents a dot on your screen.)

This topic section assumes that the form's ScaleMode measurement is set to pixels and not the default twips. If you want to work with pixels (which many graphics programmers prefer to do), set the form's ScaleMode property to 3 - Pixel.

Overview

This topic explains the graphic methods that you can apply to forms. You'll learn how to turn individual pixels on and off, draw lines, and produce other shapes. Remember that in today's world of graphical environments, you may want to incorporate graphic images and animation files inside your applications rather than work with these more primitive methods, but these methods often suffice well for simple line- and dot-oriented graphics.

Drawing with Pixels

The most fundamental graphics method, PSet, turns screen pixels on and off. Here is the syntax of PSet:

frmFormName.PSet [Step] (intX, intY) [color]

intX and intY represent the pixel column-and-row intersections that you want to turn off. (The ScaleX and ScaleY properties determine how the coordinates operate, but coordinate 0, 0 generally represents the upper-left hand pixel on the form.) The intX and intY coordinates are absolute and reference the exact form pixel coordinates unless you specify the optional Step keyword. In other words, the statement

frmForm.PSet (30, 67)

turns on the pixel at graphics x-coordinate (column) 30 and y-coordinate (row) 67. If you include the optional Step keyword, as in

frmForm.PSet Step (30, 67)

Visual Basic turns on the form's pixel located 30 and 67 pixel positions away from the last PSet method. If you performed no other PSet before this PSet Step method, VB turns on the pixel that's 30 and 67 pixels away from the upper-left hand corner of the form.

If you don't specify a color value, Visual Basic uses the form's ForeColor color-property value. You can turn a pixel off by specifying the form's BackColor property in the PSet method like this:

frmForm.PSet (300, 200) frmForm.BackColor

Although you can use PSet to draw lines and circles, the following sections describe additional methods that draw these shapes.

Drawing Lines and Boxes

Although PSet is good for individual pixels, it's slow at drawing lines and boxes because it requires that your program first calculate each pixel in the line or box. Visual Basic provides a Line method that makes drawing lines easier and faster. Rather than collect a group of PSet methods to draw a line or box, the Line method does all the work at once.

The Line method draws lines and boxes, depending on the syntax you use. The simplest syntax draws a line from one coordinate to another:

frmFormName.Line [Step] (intX1, intY1) - [Step] (intX2, intY2), [Color] [B][F]

The intX1 and intY1 values define the beginning point (coordinates) of the line; the intX2 and intY2 coordinates define where the line ends. Remember that the coordinates can't exceed the resolution of the form. The following method draws a line from pixel 100, 100 to pixel 150, 150:

frmForm.Line (100, 100) - (150, 150)

In a manner similar to PSet, the Line method's Step option draws the line relative to the starting location (the last pixel drawn or turned off). You don't have to include the starting coordinate pair because the new option knows where to begin. When you use Step, therefore, some of the coordinates may be negative, as in the following example:

frmForm.Line -Step (-15, 0)

This option tells Visual Basic to draw a line from the last pixel drawn to a point 15 pixels to the left.

Line's arguments have no mandatory order. You can draw up, down, to the left, or to the right.

If you omit the Color value, Visual Basic uses the form's ForeColor property value.

When you want to draw a box, you don't have to issue four Line methods. You can use the B option at the end of the Line method to draw a box. The two coordinate pairs, when you specify the B box option, specify the upper-left corner of the box and the lower-right corner of the box. For example, the following Line method draws a box on the form:

frmForm.Line (20, 20) - (300, 300) , , B

Be sure to type the extra comma if you don't include a Color value. Without the comma, Visual Basic issues a syntax error.

If you add the F option to the end of the Line method (F can appear only after B), Visual Basic fills in the box with the same color as the box's outline. The following, therefore, draws a solid box on your form:

frmForm.Line (20, 20) - (300, 300) , , BF

Drawing Circles

You can use the Circle method to draw circles and ellipses (elongated circles). If you want to draw circles on your form, use this syntax:

frmForm1.Circle [Step] (intX, intY) sngRadius, [Color], , , , sngAspect

The commas are required for rare placeholder values that this lesson doesn't need to discuss.

The intX and intY coordinates determine the center point of the circle. sngRadius is the distance, in pixels (or whatever the form's ScaleMode dictates), between the circle's center and its outer edge. If you include the Step keyword, the intX and intY coordinates are relative (and can be negative) from the current (last-drawn) pixel. If you don't specify a Color value, Visual Basic uses the form's ForeColor value.

The following Circle method draws a circle on the form with a center point at 320, 100 and a radius of 100 pixels:

frmForm.Circle (320, 100), 100

To draw an ellipse, you must add the sngAspect value to Circle. The aspect value has either of two effects, depending on its value. If the aspect is less than 1, the aspect stretches the circle on the vertical x-coordinate axis; and if the aspect is greater than 1, the aspect stretches the circle vertically on the y-coordinate axis.

The aspect ratio acts like a height and width measurement through the center of the ellipse. The aspect ratio acts as a multiplier of the radius in each direction. An aspect of 4, for example, means that the ellipse is vertically stretched four times the regular circle's height. An aspect ratio of 4/10/2 (or .2) means the circle is horizontally stretched five times its regular radius (one-half of 40 percent).

The following methods draw two ellipses (the first with a stretched x-radius, and the second with a stretched y-radius):

frmForm.Circle (300, 100), 50, , , , (4 / 10 / 2)

frmForm.Circle (150, 100), 50, , , , 4

Example

The procedure in Listing 24.3 randomly draws dots on the form. The form's width and height twip values are used to keep the dots within the boundaries of the form.

Listing 24.3 Randmdot.bas: Using PSet to Draw Dots On-Screen

' Randomly draw pixels

Dim intCtr As Integer

Dim intX As Integer

Dim intY As Integer

' First, set the internal randomness

Randomize Timer

' Loop to write random dots

For intCtr = 1 To 500

intX = Int(Rnd * Form1.Height) + 1

intY = Int(Rnd * Form1.Width) + 1

Form1.PSet (intX, intY) ' Turn on dot

Next intCtr

Next Step

The procedure in Listing 24.4 draws multiple boxes on the form so you can see how to draw more than just pixels.

Listing 24.4 Boxdraw.bas: Drawing Boxes On-Screen with Line

Private Sub cmdBoxes_Click()

Dim intStartX As Integer

Dim intStartY As Integer

Dim intLastX As Integer

Dim intLastY As Integer

Dim intCtr As Integer

intStartX = 0

intStartY = 0

intLastX = 1000

intLastY = 800

For intCtr = 1 To 20

frmBoxes.Line (intStartX, intStartY)-(intLastX, intLastY), , B

' Prepare for next set of boxes

intStartX = intStartX + 400

intStartY = intStartY + 400

intLastX = intLastX + 400

intLastY = intLastY + 400

Next intCtr

End Sub

Figure 24.10 shows the boxes running diagonally down the form.

FIG. 24.10

Line draws boxes more easily than setting individual pixels for boxes.

Summary

You now have a basic understanding of Visual Basic's graphic tools and methods. Although you'll not use this lesson's information to draw extremely detailed graphics, you can draw stick figures, underline titles, and enclose other controls inside customized boxes and ovals.

The Line control draws lines on your form. The Shape control draws one of several shapes, such as boxes and circles, on your form. Neither the lines nor shapes you place on the form can accept event processing, but you can place such graphics on a form to highlight special controls.

The graphics methods turns on and off screen pixels, squares, and circles on the form. As with the Line control and the Shape control, the graphic methods don't draw form elements that can accept events, but the simple graphics do accent forms.

In the next hour, "Adding Multimedia to Your Programs," you'll learn about adding multimedia capabilities to your applications. Whereas this lesson explained simple graphics, you'll be able to improve on those graphics and other multimedia components that reside in your code.

Hour 24 Quiz

  1. What does pixel stand for?
  2. What control draws circles on forms?
  3. What control draws squares on forms?
  4. What method draws lines on forms?
  5. What method draws boxes on forms?
  6. Which of the following methods is used for drawing boxes?
    1. PSet
    2. Line
    3. Box
    4. Draw
  7. True or false: The Line and Shape controls produce graphics that support properties but not events.
  8. How does the form's ScaleMode property affect the graphic coordinates that you draw?
  9. What Line method option adds a solid interior to boxes?
  10. How does the aspect ratio affect circles?

Hour 24 Homework Exercises

  1. Add a fill-color drop-down list box and a border color drop-down list box to the application at the end of Topic 2's "Next Step" section and see how the colors affect the look of your shapes.
  2. Write a simple application that asks users what they want to see from a menu. Give them a choice of a box, a rectangle, a circle, or an ellipse.
  3. Write a program that draws a picture of books on a shelf.


© 1997, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company.