INTEGRATING GRAPHICS INTO YOUR VISUAL BASIC APPLICATIONS


Visual Basic 2005 Express provides graphic support based on GDI+ (Graphics Device Interface), which it implements in the form of properties and methods made available by classes organized in the System.Drawing namespace. GDI+ provides support for managing and displaying graphic images, drawing vector graphics, and drawing text.

GDI+ draws graphics using a coordinate system. Coordinates are measured using pixels. A graphic is rendered by specifying its starting position relative to coordinates (0,0) and other required coordinates to render a particular shape based on their distance from (0,0) on the X and Y axis, as depicted in Figure 10.5.

image from book
Figure 10.5: A graphical depiction of the coordinate system employed by GDI+ when drawing graphics.

image from book
DEFINITION

GDI+ (Graphics Device Interface) is a graphics system that provides applications with the ability to create graphics and draw text for video and print output.

image from book

Working with Graphic Images

As you have seen in earlier chapters, Visual Basic makes it relatively easy to add the display of graphic images to applications using the PictureBox control. Other controls, such as the Button control, also provide the ability to display bitmaps. Visual Basic provides built-in support for numerous types of graphic files, including .bmp, .jpeg, and .gif.

image from book
DEFINITION

A pixel (picture element) is a unit of measure. The computer's display is measured in terms of the number of pixels that it displays (for example, 800 x 600, 1024 x 786, and so on).

image from book

As you have already seen, you can configure the PictureBox control's Image property to display a graphic image. You also learned through the creation of the Dice Poker game, shown in Figure 10.6, that you can preload graphic images into an ImageList control and then display these images in any control capable of displaying them.

image from book
Figure 10.6: An example of an application that uses the PictureBox and ImageList controls to work with graphics.

GDI+ support for images also includes the ability to manipulate them in many different ways, including stretching, centering, and zooming.

Drawing Vector Graphics

Instead of simply rendering a copy of an already existing graphic image, GDI+ provides Visual Basic with the ability to draw (from scratch) images using coordinates passed to various methods. Visual Basic allows you to draw on various surfaces, including Button and Form backgrounds. You can execute methods that can draw lines, ellipses, rectangles, polygons, pie shapes, arcs, curved shapes, and so on. For example, to draw a rectangle, you only have to call on the appropriate method and pass it the coordinates of the starting and end points for the figure.

Working with the Graphics Class

In order to draw a graphic, you need a surface to draw it on, such as a Form or Button control. Before you can start drawing, you must create a Graphics object for the drawing surface you intend on using. The first step in completing this task is to set up an instance of the Graphics class within your application, as demonstrated below.

 Dim MyGraphics As System.Drawing.Graphics 

Once this has been done, you call on the CreateObjects() function in order to establish a pointer to the control or form to be used as the drawing surface, as demonstrated below.

 Private Sub frmMain_Load(ByVal sender As System.Object, _   ByVal e As System.EventArgs) Handles MyBase.Load      FormGraphic = Me.CreateGraphics() End Sub 

In this example, the object variable FormGraphic has been set to use the frmMain form (Me) as a drawing surface. Once the Graphics class reference has been defined and the drawing surface established, you can begin drawing graphics within your application by calling on any of the Graphics class's methods, as listed in Table 10.1.

Table 10.1: Drawing Methods Associated with the System.Drawing.Graphics Class

Method

Description

Clear

Clears the drawing surface

DrawArc

Draws an arc

DrawBezier

Draws a bezier curve

DrawBeziers

Draws a collection of bezier curves

DrawClosedCurve

Draws a closed curve

DrawCurve

Draws a curve

DrawEllipse

Draws an ellipse

DrawIcon

Draws an icon

DrawIconUnstretched

Draws the image without scaling its image

DrawImage

Draws an image

DrawImageUnscaled

Draws an image without scaling its size

DrawLine

Draws a line

DrawLines

Draws a collection of line segments

DrawPath

Draws a graphics path

DrawPie

Draws a pie shape

DrawPolygon

Draws a polygon

DrawRectangle

Draws a rectangle

DrawRectangles

Draws a collection of rectangles

DrawString

Draws a text string

FillClosedCurve

Draws a filled curve

FillEllipse

Draws a filled ellipse

FillPath

Draws a filled path

FillPie

Draws a filled pie

FillPolygon

Draws a filled polygon

FillRectangle

Draws a filled rectangle

FillRectangles

Draws a collection of filled rectangles

FillRegion

Draws a filled region

Working with the Pen Class

One way in which to draw a graphic using the Graphics class is with the Pen class. This is done as demonstrated below.

 FormGraphic.DrawLine(pen, Coordinates) 

In this example, pen represents a Pen object and Coordinates represents the start and ending point for a line. The Pen class is located in the System.Drawing namespace. It allows you to specify how you want a given image to be drawn. One Pen property is Color, which allows you to specify the color of the line to be drawn. Another Pen property is Brush, which is used to retrieve or set a Brush object for the Pen. Using methods associated with the Brush class, you can draw filled-in shapes.

In order to specify a color when drawing shapes with the Pen class or filling in shapes with the Brush class, you can specify any of a large collection of predefined colors that are provided by these classes. Table 10.2 provides a complete list of the colors provided by these two classes.

Table 10.2: Predefined Colors Provided by the Pens and Brushes Classes

AliceBlue

DarkTurquoise

LightSkyBlue

Peru

AntiqueWhite

DarkViolet

LightSlateGray

Pink

Aqua

DeepPink

LightSteelBlue

Plum

Aquamarine

DeepSkyBlue

LightYellow

PowderBlue

Azure

DimGray

Lime

Purple

Beige

DodgerBlue

LimeGreen

Red

Bisque

Firebrick

Linen

RosyBrown

Black

FloralWhite

Magenta

RoyalBlue

BlanchedAlmond

ForestGreen

Maroon

SaddleBrown

Blue

Fuchsia

MediumAquamarine

Salmon

BlueViolet

Gainsboro

MediumOrchid

SandyBrown

Brown

GhostWhite

MediumPurple

SeaGreen

BurlyWood

Gold

MediumSeaGreen

SeaShell

CadetBlue

Goldenrod

MediumSeaGreen

Sienna

Chartreuse

Gray

MediumSlateBlue

Silver

Chocolate

Green

MediumSpringGreen

SkyBlue

Coral

GreenYellow

MediumTurquoise

SlateBlue

CornflowerBlue

Honeydew

MediumVioletRed

SlateGray

Cornsilk

HotPink

MidnightBlue

Snow

Crimson

IndianRed

MintCream

SpringGreen

Cyan

Indigo

MistyRose

SteelBlue

DarkBlue

Ivory

Moccasin

Tan

DarkCyan

Khaki

NavajoWhite

Teal

DarkGoldenrod

Lavender

Navy

Thistle

DarkGray

LavenderBlush

OldLace

Tomato

DarkGreen

LawnGreen

Olive

Transparent

DarkKhaki

LemonChiffon

OliveDrab

Turquoise

DarkMagenta

LightBlue

Orange

Violet

DarkOliveGreen

LightCoral

OrangeRed

Wheat

DarkOrange

LightCyan

Orchid

White

DarkOrchid

LightGoldenrodYellow

PaleGoldenrod

WhiteSmoke

DarkRed

LightGray

PaleGreen

Yellow

DarkSalmon

LightGreen

PaleTurquoise

YellowGreen

DarkSeaGreen

LightPink

PaleVioletRed

 

DarkSlateBlue

LightSalmon

PapayaWhip

 

DarkSlateGray

LightSeaGreen

PeachPuff

 

The following example demonstrates the syntax involved in drawing a green line using the Pen class.

 FormGraphic.DrawLine(Pen.Green, coordinates) 

Similarly, the following syntax demonstrates how to formulate a statement that fills in a red rectangle shape using the Brush class.

 FormGraphic.FillRectangle(Brush.Red, coordinates) 

Drawing Basic Shapes

The best way to learn how to work with the Graphics class is to experiment with it. Let's begin with a couple of quick examples. The first example, shown below, demonstrates how to draw a green square.

 Public Class frmMain     Private Sub btnDraw_Click(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles btnDraw.Click         'Declare an object based on the Graphics class         Dim FormGraphic As System.Drawing.Graphics         'Declare and instantiate an object based on the Pen class and         'set its color and width         Dim MyPen As New Pen(Color. Green,  3)         'Declare and instantiate an object based on the Rectangle class         'and set its  coordinates         Dim MyRectangle  As New Rectangle(20,  20,  250, 250)         'Set the form's background as the drawing surface         FormGraphic = Me.CreateGraphics()         'Draw the shape         FormGraphic.DrawRectangle(MyPen, MyRectangle)     End Sub End Class 

In this example, the program statements that draw the square shape are executed after the user clicks on the Button control labeled Draw. As you can see, it does not take many lines of code to create this simple drawing. The first statement defines an object variable named FormGraphic based on the System.Drawing.Graphics class. The second statement defines an object variable named MyPen as a Pen object, setting the object's Color property equal to green and its line width to 3 pixels (the default width is 1 pixel). The third statement defines an object variable named MyRectangle as a Rectangle object, passing the object the coordinates of the drawing's starting location (20, 20) and its length position (250, 250) relative to the upper left-hand corner of the drawing surface (frmMain). Take note of the use of the New keyword in the second and third statements. By adding this keyword, you are able to declare and instantiate an object in the same statement. The fourth statement sets the form's background as the drawing surface. The last statement executes the Graphics class's DrawRectangle method, passing it the object variables representing the Pen object and Rectangle object.

Trick 

Even though this example draws a square shape, I had to use the Rectangle class and the DrawRectangle method because there is no Square object or DrawSquare method.

Figure 10.7 shows the drawing that is produced when this example is executed.

image from book
Figure 10.7: Using the Graphics class's DrawRectangle method to draw a square.

The next example demonstrates how to draw a filled-in circle. As you can see, it is very similar to the previous example.

 Public Class frmMain     Private Sub btnDraw_Click(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles btnDraw.Click         'Declare an object based on the Graphics class         Dim FormGraphic As System.Drawing.Graphics         'Declare and instantiate a SolidBrush and set its color         Dim MyBrush As New SolidBrush(Color.Blue)         'Declare and instantiate a Rectangle and set its coordi- nates         Dim MyRectangle As New Rectangle(20, 20, 250, 250)         'Set the form's background as the drawing surface         FormGraphic = Me.CreateGraphics()         'Draw the shape         FormGraphic.FillEllipse(MyBrush, MyRectangle)     End Sub End Class 

Like the previous example, this example draws a filled-in circle only after the user has clicked on the Button control labeled Draw. The first statement defines an object variable named FormGraphic based on the System.Drawing.Graphics class. The second statement defines an object variable named MyBrush based on the SolidBrush class, setting the object's Color property equal to Blue. The third statement defines an object variable named MyRectangle based on the Rectangle class, passing the object the coordinates of the drawing's starting location (20, 20) and its length position (250, 250). I had to use the Rectangle class to outline the starting location and dimensions of the drawing because the .NET Framework does not provide an Ellipse class. Fortunately, an ellipse is drawn using the same set of coordinates as those required to draw a rectangle shape. The last statement executes the Graphics class's DrawEllipse method, passing it the object variables representing the SolidBrush object and Rectangle object.

Trick 

Even though this example draws a circle shape, I had to use the Ellipse class and the Graphics class's FillEllipse method because there is no Circle class of FillCircle method.

Figure 10.8 shows the drawing that is produced when this example is executed.

image from book
Figure 10.8: Drawing a filled-in circle using the Graphics object's FillEllipse method.

Drawing Text

In addition to displaying and drawing graphics images, Visual Basic's GDI+ implementation provides you with the ability to draw text as a graphic image using the Graphics class's Drawstring method. For example, one way to call on this method is shown below.

 Dim objName As System.Drawing.Graphics objName(TextString, FontType, BrushColor, Coordinates) 

ObjName is the name that you chose to assign to the new instance of the Graphics class. TextString represents the string to be written as a graphic. FontType identifies the type of font to be used (Arial, Courier, and so on). BrushColor specifies the color to be used and Coordinates represents the X and Y coordinates for the upper left-hand side of the starting position of the text image.

The following statement provides an example of how to create a text graphic drawing.

 Public Class frmMain     Private Sub frmMain_Paint(ByVal sender As Object, _       ByVal e As System.windows.Forms.PaintEventArgs) Handles Me.Paint         'Declare and instantiate a Font and specify property set- tings         Dim MyFont = New Font("Arial", 32, FontStyle.Bold)         'Draw the specified text and set its  color and coordinates         e.Graphics.DrawString(DateTime.Now(), MyFont, Brushes.Red, 10, 50)     End Sub End Class 

In this example, the statements that draw the text image have been placed inside the frmMain_Paint procedure. This event procedure automatically executes anytime a form needs to be repainted, including when the form is first displayed. In this example's first statement, a Font object variable named MyFont is instantiated and passed arguments that set its font type, font size, and font style. The second statement draws a text string using the Graphics class's Drawstring method. Notice that the Graphics class is referenced as e.Graphics in this example. I was able to set up the reference to the Graphics class this way because the Paint event procedure automatically generates a reference to the System.Drawing class in the form of a variable named e.

The graphic text to be written is supplied by the DateTime class's Now() method. Font information is supplied by passing the Drawstring method the MyFont object. Finally, the Brushes.Red argument is used to specify the color of the text, and the coordinates (10, 50) are passed in order to specify the location where the graphic text should start being written.

Figure 10.9 shows the output generated when this example is run.

image from book
Figure 10.9: Visual Basic allows you to draw text as a graphic.




Microsoft Visual Basic 2005 Express Edition Programming for the Absolute Beginner
Microsoft Visual Basic 2005 Express Edition Programming for the Absolute Beginner
ISBN: 1592008143
EAN: 2147483647
Year: 2006
Pages: 126

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net