Chapter 15 Adding Graphics and Animation Effects 377
Whether you’re creating simple screen shots or building complex drawings, it’s important to
be able to render many of the standard geometric shapes in your programs. Table 15-1 lists
several of the fundamental drawing shapes and the methods you use in the System.Drawing.
Graphics class to create them.
TABLE 15-1 Useful Shapes and Methods in the System.Drawing.Graphics Class
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 FillPolygon.
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 red 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 Graphics
Dim PenColor As New Pen(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 reference the class.