Microsoft Visual Basic 2005 Step by Step (Step by Step (Microsoft))
Adding Artwork by Using the System.Drawing Namespace
Adding ready-made artwork to your programs is easy in Visual Basic. Throughout this book you've experimented with adding bitmaps and icons to a form by using picture box objects. Now you'll learn how to create original artwork on your forms by using the GDI+ functions in the System.Drawing namespace, an application programming interface (API) provided by the Microsoft .NET Framework for creating two-dimensional vector graphics, imaging, and typography within the Microsoft Windows operating system. The effects that you create can add color, shape, and texture to your forms.
Using a Form's Coordinate System
The first thing to learn about creating graphics is the layout of the form's predefined coordinate system. In Visual Basic, each form has its own coordinate system. The coordinate system's starting point, or origin, is the upper-left corner of a form. The default coordinate system is made up of rows and columns of device-independent picture elements, or pixels, which represent the smallest points that you can locate, or address, on a Visual Basic form.
In the Visual Basic coordinate system, rows of pixels are aligned to the x-axis (horizontal axis), and columns of pixels are aligned to the y-axis (vertical axis). You define locations in the coordinate system by identifying the intersection of a row and a column with the notation (x, y). The (x, y) coordinates of the upper-left corner of a form are always (0, 0). The following illustration shows how the location for a picture box object on the form is described in the Visual Basic coordinate system:
Visual Basic works along with your computer's video display driver software to determine how pixels are displayed on the form and how shapes such as lines, rectangles, curves, and circles are displayed. Occasionally, more than one pixel is turned on to display a particular shape, such as the line drawing shown in the following illustration. The logic that handles this type of rendering isn't your responsibility—it's handled by your display adapter and the drawing routines in the GDI+ graphics library. The following illustration shows a zoomed-in view of the distortion or jagged edges you sometimes see in Visual Basic and Windows applications:
The System.Drawing.Graphics Class
The System.Drawing namespace includes numerous classes for creating artwork and special effects in your programs. In this section, you'll learn a little about the System.Drawing.Graphics class, which provides methods and properties for drawing shapes on your forms. You can learn about the other classes by referring to the Visual Studio online Help.
Whether you're creating simple illustrations or building complex drawings, it's important to be able to render many of the standard geometric shapes in your programs. The following table lists several of the fundamental drawing shapes and the methods you use in the System .Drawing.Graphics class to create them.
Shape | Method | Description |
Line | DrawLine | Simple line connecting two points. |
Rectangle | DrawRectangle | Rectangle or square connecting four points. |
Arc | DrawArc | Curved line connecting two points (a portion of an ellipse). |
Circle/Ellipse | DrawEllipse | Elliptical shape that is “bounded” by a rectangle. |
Polygon | DrawPolygon | Complex shape with a variable number of points and sides (stored in an array). |
Curve | DrawCurve | A curved line that passes through a variable number of points (stored in an array); complex curves called cardinal splines can also be drawn with this method. |
Bézier splines | DrawBezier | A curve drawn by using four points. (Points two and three are “control” points.) |
In addition to the preceding methods, which create empty or “non-filled” shapes, there are several methods for drawing shapes that are filled with color. These methods usually have a “Fill” prefix, such as FillRectangle, FillEllipse, and Fill Polygon.
When you use a graphics method in the System.Drawing.Graphics class, you need to create a Graphics object in your code to represent the class and either a Pen or Brush object to indicate the attributes of the shape you want to draw, such as line width and fill color. The Pen object is passed as one of the arguments to the methods that aren't filled with color. The Brush object is passed as an argument when a fill color is desired. For example, the following call to the DrawLine method uses a Pen object and four integer values to draw a line that starts at pixel (20, 30) and ends at pixel (100, 80). The Graphics object is declared by using the name GraphicsFun, and the Pen object is declared by using the name PenColor.
Dim GraphicsFun As System.Drawing.Graphics Dim PenColor As New System.Drawing.Pen(System.Drawing.Color.Red) GraphicsFun = Me.CreateGraphics GraphicsFun.DrawLine(PenColor, 20, 30, 100, 80)
The syntax for the DrawLine method is important, but also note the three lines above it, which are required to use a method in the System.Drawing.Graphics class. You must create variables to represent both the Graphics and Pen objects, and the Graphics variable needs to be instantiated by using the CreateGraphics method for the Windows form. Note that the System .Drawing.Graphics namespace is included in your project automatically—you don't need to include an Imports statement in your code to declare the necessary class.
Using the Form's Paint Event
If you test the previous DrawLine method in a program, you'll notice that the line you created lasts, or persists, on the form only as long as nothing else covers it up. If a dialog box appears on the form momentarily and covers the line, the line is no longer visible when the entire form is visible again. The line also disappears if you minimize the form window and then maximize it again. To address this shortcoming, you need to place your graphics code in the form's Paint event procedure so that each time the form is refreshed, the graphics are repainted, too.
In the following exercise, you'll create three shapes on a form by using the form's Paint event procedure. The shapes you draw will continue to persist even if the form is covered or minimized.
Create line, rectangle, and ellipse shapes
Start Visual Studio, and create a new Windows Application project named My Draw Shapes.
Resize the form so that it's higher and wider than the default form size.
You'll need a little extra space to create the graphics shapes. You won't be using any Toolbox controls, however. You'll create the shapes by placing program code in the form's Form1_Paint event procedure.
Set the Text property of Form1 to “Draw Shapes”.
Click the View Code button in Solution Explorer to display the Code Editor.
In the Class Name list box, click Form1 Events.
Form1 Events is the list of events in your project associated with the Form1 object.
In the Method Name list box, click the Paint event.
The Form1_Paint event procedure appears in the Code Editor.
This event procedure is where you place code that should be executed when Visual Basic refreshes the form.
Type the following program code:
'Prepare GraphicsFun variable for graphics calls Dim GraphicsFun As System.Drawing.Graphics GraphicsFun = Me.CreateGraphics 'Use a red pen color to draw a line and an ellipse Dim PenColor As New System.Drawing.Pen(System.Drawing.Color.Red) GraphicsFun.DrawLine(PenColor, 20, 30, 100, 80) GraphicsFun.DrawEllipse(PenColor, 10, 120, 200, 160) 'Use a green brush color to create a filled rectangle Dim BrushColor As New SolidBrush(Color.Green) GraphicsFun.FillRectangle(BrushColor, 150, 10, 250, 100) 'Create a blue cardinal spline curve with four points Dim Points() As Point = {New Point(358, 280), _ New Point(300, 320), New Point(275, 155), New Point(350, 180)} For tension As Single = 0 To 2.5 Step 0.5 GraphicsFun.DrawCurve(Pens.DodgerBlue, Points, tension) Next
This sample event procedure draws four graphic shapes on your form: a red line, a red ellipse, a green-filled rectangle, and a blue cardinal spline (a complex curve made up of five lines). To enable graphics programming, the routine declares a variable named GraphicsFun in the code and uses the CreateGraphics method to activate or instantiate the variable. The PenColor variable of type System.Drawing.Pen is used to set the drawing color in the line and ellipse, and the BrushColor variable of type SolidBrush is used to set the fill color in the rectangle. These examples are obviously just the tip of the graphics library iceberg—there are many more shapes, colors, and variations that you can create by using the methods in the System.Drawing.Graphics class.
TIP
The complete Draw Shapes program is located in the c:\vb05sbs\chap15\draw shapes folder.
Click the Start Debugging button on the Standard toolbar to run the program.
Visual Basic loads the form and executes the form's Paint event. Your form looks like this:
Minimize the form, and then restore it again.
The form's Paint event is executed again, and the graphics shapes are refreshed on the form.
Click the Close button to end the program.
Click the Save All button on the Standard toolbar to save the project, and specify the c:\vb05sbs\chap15 folder as the location.
Now you're ready to move on to some simple animation effects.