Lesson 1: Using GDI

Lesson 1: Using GDI+

Microsoft Windows is a graphical interface. Users interact with applications through windows, which are graphical representations of application data and options. To take advantage of the rich user experience that Windows offers, you should design applications so that they expose their functionality to the user graphically. Although the .NET Framework provides a wide array of graphical controls and methods that allow you to create fully visual applications, you might want to render your own graphic content or create a custom appearance for a control. To do so, and also to take full advantage of the features afforded by the Windows operating system, you must learn to use the Graphic Device Interface (GDI). In the .NET Framework, this interface is fully managed and is referred to as GDI+. Classes in the .NET Framework that expose the GDI+ functionality are found in the System.Drawing namespace and associated namespaces.

After this lesson, you will be able to

  • Describe how to create and use a Graphics object

  • Explain how to use pens, brushes, and colors

  • Describe how to draw an outlined shape and a filled shape

  • Describe how to render text

  • Describe how to create a GraphicsPath and a Region

Estimated lesson time: 40 minutes

GDI+ is the name given to the .NET Framework managed implementation of the GDI, which is used to display graphical information on the computer screen. This interface is wrapped into six namespaces, broken down by functionality.

The System.Drawing Namespaces

The System.Drawing namespaces expose vast functionality. Although an exhaustive dissection of these namespaces is beyond the scope of this book, this lesson will familiarize you with the techniques for accessing the classes and methods they contain. The general functions of the classes contained in the namespaces are summarized in Table 7.1.

Table 7-1. The System.Drawing Namespaces

Namespace

Contains

System.Drawing

Most of the classes involved in rendering graphical content to the screen. This is the primary namespace used for graphics programming.

System.Drawing.Design

Classes that provide additional functionality for design-time graphics operations.

System.Drawing.Drawing2D

Classes that render advanced visual effects.

System.Drawing.Imaging

Classes that allow advanced manipulation of image files.

System.Drawing.Printing

Classes that facilitate printing content.

System.Drawing.Text

Classes that facilitate advanced manipulation of fonts.

Almost all the classes that you need to render graphics are provided in the System.Drawing namespace. For advanced rendering, you also might need classes in the System.Drawing.2D namespace, and to enable printing, you will need classes in the System.Drawing.Printing namespace.

The Graphics Object

The Graphics object, located in the System.Drawing namespace, is the principal object used to render graphics. A Graphics object represents the drawing surface of a visual element, such as a form, a control, or an Image object. Thus, a form has an associated Graphics object that is used to draw inside the form; a control has an associated Graphics object that is used to draw inside the control, and so on. The Graphics object does the actual rendering of visual elements.

Because each Graphics object must be associated with a visual element, you cannot directly instantiate one with a call to the constructor. Instead, you must create a Graphics object directly from the visual element. Classes that inherit from Control (including Form) expose a CreateGraphics method that allows you to get a reference to the Graphics object associated with that control. The following code example demonstrates how to access the Graphics object of a Form named myForm:

Visual Basic .NET

Dim myGraphics As System.Drawing.Graphics myGraphics = myForm.CreateGraphics()

Visual C#

System.Drawing.Graphics myGraphics; myGraphics = myForm.CreateGraphics();

The Graphics object thus created can then be used to render graphics on that form.

If you are working with images, you can use the Graphics.FromImage method to create a Graphics object associated with a particular Image. This method is a static method, so you do not need an active reference to a Graphics object to call it. The Image object can be any object that inherits from the Image class, such as an instance of Bitmap. The following code example demonstrates how to create a Bitmap object from a file and then create an associated Graphics object:

Visual Basic .NET

Dim myImage As New Bitmap("C:\myImage.bmp") Dim myGraphics As System.Drawing.Graphics myGraphics = Graphics.FromImage(myImage)

Visual C#

Bitmap myImage = new Bitmap("C:\\myImage.bmp"); System.Drawing.Graphics myGraphics; myGraphics = Graphics.FromImage(myImage);

Note that the Image does not have to be visible to create a Graphics object or perform manipulations with it.

Coordinates

Rendering takes place on the screen in the region set by the bounds of the control. This region is measured in two-dimensional coordinates consisting of x and y values. By default, the origin of the coordinate system for each control is the upper-left corner, which has coordinates of (0,0). The coordinates are measured in screen pixels. The System.Drawing namespace contains a variety of structures used to describe locations or regions within the coordinate system. These structures are summarized in Table 7.2.

Table 7-2. Coordinate and Shape Structures

Structure

Description

Point

Represents a single point with Integer (int) values of x and y

PointF

Represents a single point with Single (float) values of x and y

Size

Represents a rectangular size consisting of paired Height and Width values as integers

SizeF

A rectangular size consisting of a pair of Single (float) values, representing Height and Width

Rectangle

A representation of a rectangular region of the drawing surface with Top, Bottom, Left, and Right edges specified by Integer (int) values

RectangleF

A representation of a rectangular region of the drawing surface with Top, Bottom, Left, and Right edges specified by Single (float) values

As Table 7.2 suggests, there are two flavors of structure. Some structures take Integer values while others take floating-point values. Integer types, such as Point, Size, and Rectangle, can be implicitly converted to their floating-point counterparts. To convert a floating-point type to an integer type, however, you must explicitly convert each coordinate from the floating-point type to the integer type. For example:

Visual Basic .NET

Dim myPoint As Point Dim myPointF As New PointF(13.5,33.21) myPoint = New Point(CInt(myPointF.X), CInt(myPointF.Y))

Visual C#

Point myPoint; PointF myPointF = new PointF(13.5F,33.21F); myPoint = new Point((int)myPointF.X, (int)myPointF.Y);

It is important to note the relationship between the Size structures and the Rectangle structures. Although both denote a rectangular region of the drawing surface, Size structures indicate only the size of a rectangle and do not specify position. Rectangle structures, on the other hand, indicate the actual position of a specific rectangle on the drawing surface. You can create a Rectangle by supplying a Size plus a Point that serves as the upper-left corner of the Rectangle on the drawing surface. For example:

Visual Basic .NET

Dim myOrigin As New Point(10, 10) Dim mySize As New Size(20, 20) ' Creates a 20 by 20 Rectangle with Point(10,10) as the upper ' left corner Dim myRectangle As New Rectangle(myOrigin, mySize)

Visual C#

Point myOrigin = new Point(10, 10); Size mySize = new Size(20, 20); // Creates a 20 by 20 Rectangle with Point(10,10) as the upper // left corner Rectangle myRectangle = new Rectangle(myOrigin, mySize);

Drawing Shapes

The Graphics object encapsulates a variety of methods for rendering simple and complex shapes to the screen. These methods come in two general varieties. Those that begin with Draw are used to draw line structures, such as lines, arcs, and outlines of shapes; those that begin with Fill are used to render solid shapes, such as filled rectangles, ellipses, or polygons. These methods are summarized in Tables 7.3 and 7.4.

Table 7-3. Methods for Drawing Line Structures

Method

Description

DrawArc

Draws an arc representing a portion of an ellipse

DrawBezier

Draws a Bezier spline

DrawBeziers

Draws a series of Bezier splines

DrawClosedCurve

Draws a closed curve through a series of points

DrawCurve

Draws an open curve through a series of points

DrawEllipse

Draws an ellipse defined by a bounding rectangle

DrawLine

Draws a line connecting two points

DrawLines

Draws a series of lines connecting an array of points

DrawPath

Draws a specified GraphicsPath object representing a complex shape

DrawPie

Draws a pie shape representing a slice of an ellipse

DrawPolygon

Draws a polygon created from a specified series of points

DrawRectangle

Draws a rectangle

DrawRectangles

Draws a series of rectangles

Table 7-4. Methods for Rendering Filled Shapes

Method

Description

FillClosedCurve

Renders a filled closed curve specified by an array of points

FillEllipse

Renders a filled ellipse

FillPath

Renders a filled GraphicsPath object representing a complex shape

FillPie

Renders a filled pie shape representing a slice of an ellipse

FillPolygon

Renders a filled polygon specified by an array of points

FillRectangle

Renders a filled rectangle

FillRectangles

Renders a series of filled rectangles

FillRegion

Renders a filled Region object that usually corresponds to a complex shape

Each of these methods takes a different set of parameters that specify the coordinate points and location of the shapes to be drawn. Each method also requires an object to actually perform the rendering. For line structures, this object is a Pen. For filled shapes, the required object is a Brush.

Color, Brushes, and Pens

Color, brushes, and pens are used to determine how a graphical image will render. Pens render lines and arcs, brushes render filled shapes, and color specifies the color to display.

Color

The Color structure, which represents a single color, is found in the System.Drawing namespace. Individual colors are derived from four values: Alpha, which represents transparency, plus Red, Green, and Blue. Each of these parameters can have a range from 0 to 255. You can create new colors by specifying values with the Color.FromArgb method, like this:

Visual Basic .NET

Dim myColor As Color myColor = Color.FromArgb(128, 255, 12, 43)

Visual C#

Color myColor; myColor = Color.FromArgb(128, 255, 12, 43);

If you are working solely with opaque colors, you can omit the Alpha parameter and specify only Red, Green, and Blue values, as follows:

Visual Basic .NET

Dim myColor As Color myColor = Color.FromArgb(255, 12, 43)

Visual C#

Color myColor; myColor = Color.FromArgb(255, 12, 43);

You can also specify one of the named colors in the .NET Framework. These colors are provided to allow easy reference to known colors. The following code demonstrates an example:

Visual Basic .NET

Dim myColor As Color myColor = Color.Tomato 

Visual C#

Color myColor; myColor = Color.Tomato;

Brushes

Brushes are used to render filled shapes. All brushes derive from the abstract base class Brush and provide different implementations of objects used to render filled objects in different styles. The different types of brushes and the namespaces in which they can be found are summarized in Table 7.5.

Table 7-5. Types of Brushes

Type

Namespace

Description

SolidBrush

System.Drawing

A brush that uses a single, solid color

TextureBrush

System.Drawing

A brush that fills closed objects with an image

HatchBrush

System.Drawing.Drawing2D

A brush that paints using a hatched pattern

LinearGradientBrush

System.Drawing.Drawing2D

A brush that blends two colors along a gradient

PathGradientBrush

System.Drawing.Drawing2D

A brush that renders complex gradient effects

Creating a SolidBrush is as simple as specifying the color, as shown here:

Visual Basic .NET

Dim myBrush As New SolidBrush(Color.PapayaWhip)

Visual C#

SolidBrush myBrush = new SolidBrush(Color.PapayaWhip);

Other brushes have more complex constructors and require additional parameters. For example, a TextureBrush requires an Image object. A LinearGradientBrush requires two colors and a variety of other parameters, depending on which constructor is used.

Pens

Pens are used to draw lines and arcs, and they can be used to apply a variety of special effects to line structures. There is only one Pen class, and it cannot be inherited. Creating a pen can be as easy as specifying the color, for example:

Visual Basic .NET

Dim myPen As New Pen(Color.BlanchedAlmond)

Visual C#

Pen myPen = new Pen(Color.BlanchedAlmond);

This creates a pen with a color of blanched almond and a default width of one. You can also specify other widths in the constructor, as in this example:

Visual Basic .NET

Dim myPen As New Pen(Color.Lime, 4)

Visual C#

Pen myPen = new Pen(Color.Lime, 4);

This example creates a pen with a width of four. You can also create a pen from an existing brush. This allows you to create a pen that matches the visual scheme you are using in your interface and is a particularly useful technique if you want to use complex shading or other effects. The following code example demonstrates how to create a pen from a preexisting brush named myBrush:

Visual Basic .NET

Dim myPen As New Pen(myBrush)

Visual C#

Pen myPen = new Pen(myBrush);

You can also specify a width when creating a pen from a brush.

System Colors, Brushes, and Pens

When designing the user interface for your application, you might want any custom UI components to have the same look and feel as the system that the application will run on. The .NET Framework exposes colors used by the system through the SystemColors class. This class contains a set of static members that expose the colors currently used by the system. Thus, you can design custom UI elements with system colors so that at run time they will render using the current system palette. The following code example shows how to access one of the system colors:

Visual Basic .NET

Dim myColor As Color = SystemColors.HighlightText

Visual C#

Color myColor = SystemColors.HighlightText;

In addition to the SystemColors class, the .NET Framework provides a SystemPens class and a SystemBrushes class that provide access to default pens and brushes. You can use the members of these classes just as you would use any other Pen or SolidBrush.

Rendering Simple Shapes

You can use the methods provided by the Graphics class to draw a variety of simple shapes. The methods that can be used for these procedures were summarized in Table 7.3.

All of the methods that render line structures require a valid Pen object. Likewise, methods for rendering filled shapes require a valid Brush object. You also must supply whatever other objects the appropriate method requires. For example, the following code example demonstrates how to render an outlined rectangle with the DrawRectangle method:

Visual Basic .NET

' Creates the Rectangle object Dim myRectangle As New Rectangle(0, 0, 30, 20) ' Creates the Graphics object that corresponds to the form Dim g As Graphics = Me.CreateGraphics() ' Uses a system pen to draw the rectangle g.DrawRectangle(SystemPens.ControlDark, myRectangle) ' Disposes the Graphics object g.Dispose()

Visual C#

// Creates the Rectangle object Rectangle myRectangle = new Rectangle(0, 0, 30, 20); // Creates the Graphics object that corresponds to the form Graphics g = this.CreateGraphics(); // Uses a system pen to draw the rectangle g.DrawRectangle(SystemPens.ControlDark, myRectangle); // Disposes the Graphics object g.Dispose();

Because they hold a lot of system resources, you should always call Dispose on your Graphics objects when you are finished with them. Failure to call Dispose can degrade application performance. You also should call Dispose on any Pen or Brush objects you create. The following code example demonstrates how to render a filled ellipse and then properly dispose of the Brush and Graphics objects:

Visual Basic .NET

Dim myBrush As New SolidBrush(Color.MintCream) Dim g As Graphics = Me.CreateGraphics() ' The ellipse will be inscribed within the rectangle Dim myRectangle As New Rectangle(0, 0, 30, 20) g.FillEllipse(myBrush, myRectangle) ' Dispose the Graphics object and the Brush g.Dispose() myBrush.Dispose()

Visual C#

SolidBrush myBrush = new SolidBrush(Color.MintCream); Graphics g = this.CreateGraphics(); // The ellipse will be inscribed within the rectangle Rectangle myRectangle = new Rectangle(0, 0, 30, 20); g.FillEllipse(myBrush, myRectangle); // Dispose the Graphics object and the Brush g.Dispose(); myBrush.Dispose();

To render a simple shape

  1. Create a Graphics object that represents the drawing surface on which you want to render.

  2. Create any additional objects you might need, such as Point, Rectangle, Pen (for line structures), or Brush (for filled shapes).

  3. Call the appropriate method of the Graphics object.

  4. Dispose any Pen or Brush objects that you created by calling the Dispose method of that object.

  5. Dispose the Graphics object.

Rendering Text

You can use the Graphics object to render text by using the DrawString method, which renders a string of text on the screen. The text is displayed in a specified font and is rendered using a specified Brush object. The method also requires some kind of location in the coordinate system of the drawing surface, such as a PointF to designate the upper-left corner. The following code example demonstrates how to render a string with the Graphics.DrawString method:

Visual Basic .NET

' This example uses the SystemBrush class to supply one of the ' system brushes Dim g As Graphics = me.CreateGraphics() Dim myString As String = "Hello World" Dim myFont As New Font("Times New Roman", 36, FontStyle.Regular) ' The final two parameters are X and Y coordinates g.DrawString(myString, myFont, SystemBrushes.Highlight, 0, 0) ' Always dispose your Graphics object g.Dispose()

Visual C#

// This example uses the SystemBrush class to supply one of the // system brushes Graphics g = this.CreateGraphics(); String myString = "Hello World"; Font myFont = new Font("Times New Roman", 36, FontStyle.Regular); // The final two parameters are X and Y coordinates g.DrawString(myString, myFont, SystemBrushes.Highlight, 0, 0); // Always dispose your Graphics object g.Dispose();

To render text

  1. If necessary, create Font and Brush objects appropriate to the style in which you want to render the string.

  2. Obtain a reference to the Graphics object associated with the drawing surface on which you want to render the text.

  3. Call the Graphics.DrawString method, specifying the appropriate String, Font, Brush, and location.

  4. Dispose the Graphics object by calling Graphics.Dispose.

Rendering Complex Shapes

At times, you will find it necessary to render complex shapes. Although simple shapes such as rectangles, ellipses, and polygons have built-in methods to facilitate their rendering, complex shapes require a little more planning. The primary object used for rendering complex shapes is the GraphicsPath object. A member of the System.Drawing.Drawing2D namespace, the GraphicsPath object can describe any kind of closed shape or set of shapes. Thus, you could have a GraphicsPath that consists of ellipses, rectangles, and other regular objects, combined with irregular or amorphous shapes.

Creating a GraphicsPath

You create a GraphicsPath object by making a call to one of the GraphicsPath constructors. The simplest GraphicsPath constructor takes no parameters.

Visual Basic .NET

Dim myPath As New Drawing2D.GraphicsPath()

Visual C#

GraphicsPath myPath = new Drawing2D.GraphicsPath();

Additionally, you can specify arrays of points and bytes that describe the Graphics Path. The array of points provides coordinates to map the path to, and the array of bytes describes what kind of line passes through the points. To create more readable and maintainable code, you can convert the array of bytes from the System.Drawing.Drawing2D.PathPointType enum. The following code example creates a very simple GraphicsPath:

Visual Basic .NET

' This example assumes Imports System.Drawing.Drawing2D Dim myPath As New GraphicsPath(New Point() {New Point(1, 1), _ New Point(32, 54), New Point(33, 5)}, New Byte() _ {CType(PathPointType.Start, Byte), CType(PathPointType.Line, _ Byte), CType(PathPointType.Bezier, Byte)})

Visual C#

// This example assumes using System.Drawing.Drawing2D GraphicsPath myPath = new GraphicsPath(new Point[] {new Point(1, 1), new Point(32, 54), new Point(33, 5)}, new byte[] { (byte)PathPointType.Start, (byte)PathPointType.Line, (byte)PathPointType.Bezier});

Once it is created, you can add figures to the GraphicsPath. A figure represents a closed shape including simple shapes, such as ellipses and rectangles, and more complex shapes, such as irregular curves and font characters.

The GraphicsPath class contains several methods that allow you to add figures to the path. These are summarized in Table 7.6.

Table 7-6. Methods for Adding Figures

Method

Description

AddClosedCurve

Adds a closed curve described by an array of points to the GraphicsPath

AddEllipse

Adds an ellipse to the GraphicsPath

AddPath

Adds a specified instance of GraphicsPath to the current path

AddPie

Adds a pie shape to the GraphicsPath

AddPolygon

Adds a polygon described by an array of points to the GraphicsPath

AddRectangle

Adds a rectangle to the GraphicsPath

AddRectangles

Adds an array of rectangles to the GraphicsPath

AddString

Adds a graphical representation of a string to the GraphicsPath, in the specified font

In addition to directly adding figures to the GraphicsPath, you can create figures by adding lines, arcs, and curves. You can begin a figure by calling GraphicsPath.StartFigure. After calling this method, you can use methods supplied by the GraphicsPath class to add line elements to the figure. Once you have completed your figure, you can call GraphicsPath.CloseFigure to close the figure. Doing so causes the last point to be created in a figure to connect automatically with the first one, as the following code example demonstrates:

Visual Basic .NET

' This example assumes Imports System.Drawing.Drawing2D Dim myPath As New GraphicsPath() myPath.StartFigure() ' Insert code to add line elements to the figure here myPath.CloseFigure()

Visual C#

// This example assumes using System.Drawing.Drawing2D GraphicsPath myPath = new GraphicsPath(); myPath.StartFigure(); // Insert code to add line elements to the figure here myPath.CloseFigure();

If you call StartFigure and then call StartFigure again without calling CloseFigure, the first figure is left open.

NOTE
When rendered at run time, any open figures close by adding a line between the first and last points to be created in the figure.

Table 7.7 summarizes the GraphicsPath methods that add line elements to a figure.

Table 7-7. Methods for Adding Line Elements

Method

Description

AddArc

Adds an arc to the current figure

AddBezier

Adds a Bezier curve to the current figure

AddBeziers

Adds a series of connected Bezier curves to the current figure

AddCurve

Adds a curve described by an array of points to the current figure

AddLine

Adds a line to the current figure

AddLines

Adds a series of connected lines to the current figure

To render a complex shape

  1. Obtain a reference to the Graphics object associated with the drawing surface you want to render on.

  2. Create a new instance of the GraphicsPath class.

  3. Add figures to the GraphicsPath using the methods the GraphicsPath class provides.

  4. Call Graphics.DrawPath to draw the outline of the path or Graphics.FillPath to draw a filled GraphicsPath.

  5. Dispose the Graphics object.

Lesson Summary

  • The Graphics object is the principal object used to render graphics. It represents a drawing surface and provides methods for rendering to that drawing surface.

  • Pens, brushes, and colors are objects that are used to control how a graphic is rendered to a drawing surface. Pens draw lines, brushes fill shapes, and colors represent colors. You can use SystemPens, SystemBrushes, and SystemColors to maintain a coherent appearance with the rest of the application.

  • Simple shapes and text can be rendered using the methods provided by the Graphics object.

  • Complex shapes should be defined in terms of a GraphicsPath object, which exposes a variety of methods to facilitate defining complex shapes. When complete, a GraphicsPath object can be rendered by the Graphics object.



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[.  .. ]0-316
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[. .. ]0-316
ISBN: 735619263
EAN: N/A
Year: 2003
Pages: 110

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