Ziff-Davis Enterprise 
DevSource: Microsoft Developer Resource
Add OnsArchitectureLanguagesTechniquesUsing VSForums
 
Home arrow Using VS arrow The GraphicsPath Class: the Graphics Programmer's Friend
The GraphicsPath Class: the Graphics Programmer's Friend
By Peter Aitken

Rate This Article:
Add This Article To:
If your apps use any kind of graphics, you'll be amazed by how much time this single class can save you. This may indeed be the path of least resistance.

One of the things I like best about the .NET Framework is its support for graphics operations. There has been an almost complete break with the old way of doing graphics, such as that supported by Visual Basic version 6. Functionality for shapes, fills, patterns, and fonts are not encapsulated in a set of classes that make the programmer's task a lot easier. The graphics class library also contains some classes that are not directly drawing-related, but which help organize and simplify your graphics programming. The GraphicsPath class is one of them.

In a nutshell, the GraphicsPath class lets you encapsulate a series of drawing operations in a single object. Anything that .NET can draw directly to the screen can also be put in a GraphicsPath object: lines, shapes, text, fills, and so on. Okay, fine — then what? Here's where the utility of the class becomes clear. Once your drawing operations are all in a GraphicsPath, you can treat them as a single object; you can draw, transform, rotate, or resize then all in a single operation.

ADVERTISEMENT

For example, imagine a program that creates bar charts, each of which contains dozens of individual drawn objects (lines, fills, text, etc.). Sure, you could draw the chart directly to the screen, but if you needed to change its size or rotate it for printing you would have to resize or rotate each component separately. By first putting the entire chart in a GraphicsPath, you could do any of these operations in a single step. The programming saved can be considerable! As with other drawing classes, the GraphicsPath class is part of the System.Drawing.Drawing2D namespace.

Adding to a GraphicsPath

The GraphicsPath class has a set of methods for adding shapes, lines, and text. These methods parallel the Graphics class's method for drawing directly to the screen or printer. For example, you use the Graphics.DrawArc() method to draw an arc on screen and the GraphicsPath.AddArc() method to add an arc to a path. The names are similar; each Graphics.Drawxxxx() method is paralleled by a GraphicsPath.Addxxxx() method. The major difference is that Drawxxxx() specifys a pen to use, while the Addxxxx() methods do not (you specify a pen when you draw the entire path, not when adding elements to it). The methods to add elements to a path are listed below. I will not go into detail because you can find the relevant information in the on-line help.

  • AddArc()
  • AddPie()
  • AddBezier()
  • AddBeziers()
  • AdddCurve()
  • AddClosedCurve()
  • AddEllipse()
  • AddLine()
  • AddPolygon()
  • AddRectangle()
  • AddString()
  • AddPath()

The last method, AddPath(), deserves special mention. You use it to add one GraphicsPath to another. That's very useful when you want to define several independent paths and need to combine them for certain operations.

It's time to look at a GraphicsPath example. Create a Windows Forms C# project and put the following code in the Paint event handler for the form. When you run the program you'll see the display shown in the figure.

GraphicsPath gp = new GraphicsPath();
string msg = "Graphics Paths!";
//Add a line and an ellipse.
gp.AddLine(10, 10, 400, 10);
gp.AddEllipse(10, 80, 400, 60);
//Set up to add some text to the path.
FontFamily ff = new FontFamily("Arial");
int fs = (int)FontStyle.Italic;
int emSize = 50;
Point origin = new Point(10,20);
StringFormat sf = StringFormat.GenericDefault;
//Add the text.
gp.AddString(msg, ff, fs, emSize, origin, sf);
//Display the path on-screen.
Pen p = new Pen(Color.Black, 2);
e.Graphics.DrawPath(p, gp);

Figures and Connections in a Path

The graphics operations encapsulated in a GraphicsPath object are referred to collectively as a path. A path consists of one or more figures, or subpaths. Each subpath consists of either a series of connected lines and curves or a single geometric primitive (closed shapes, such as rectangles and ellipses). When you add the first item to a path, it becomes part of a new figure. Subsequent items can either be added to an existing figure in the path or can become the start of a new figure. You need to understand how the GraphicsPath object handles the relationships between figures.

Suppose you add two lines to a GraphicsPath object:

GraphicsPath gp = new GraphicsPath();
gp.AddLine(10, 10, 160, 240);
gp.AddLine(240, 240, 280, 10);

Note that these two lines are not connected. But, because they are part of the same figure, and figures are by definition connected, the GraphicsPath object adds an implicit line connecting them. When you display this path you will see three lines:

  • The first explicitly drawn line from (10,10) to (160,240)
  • The second explicitly drawn line from (240,240) to (280,10)
  • The implicit line added by the GraphicsPath object from the end of the first line (160,240) to the beginning of the second line (240,240).

As mentioned earlier, graphics primitives are always separate figures. But suppose you are drawing multiple lines and want them to remain separate without being connected by an implicit line? Then you need to end the current figure and start a new one with these methods:

  • CloseFigure(): Closes the current figure and starts a new one (the next line drawn will be part of the new figure). Closing means that an implicit line is drawn from the figure's start point to its end point to create a closed figure (if the figure is not already closed). For example, if you draw a 2-line figure in a "V" shape then close it, an implicit line will be drawn to close the figure and make a triangle.
  • StartFigure(): Starts a new figure without closing the current one.

Drawing and Transforming Paths

You already saw, in the code example above, how to draw a GraphicsPath object to a drawing surface by calling the Graphics object's DrawPath method. This method takes a Pen object and a GraphicsPath object as its two arguments. Of course, as with other .NET drawing operations, the properties of the Pen object determine the color, width, and style of the lines used to draw the path.

In .NET, a transforms let you modify an image in various ways, such as changing its position, flipping it, changing its size, stretching it in one or more directions, or rotating it. Most transforms are defined as a transformation matrix, a topic that I cannot go into here. Once you have the matrix that defines the desired transform, you can apply it to a GraphicsPath object by using the Transform() method, passing the matrix as the method's one argument.

Filling Paths

The PathGradientBrush class is designed specifically for filling paths with color gradients (it can be used fill other shapes as well, but that's another topic). The brush is created based on a path, which defines the shape of the gradient. You also specify the color of the center of the gradient and one or more colors for the surround. Here's a simple example that does the following:

  1. Creates a GraphicsPath object and adds an ellipse to it.
  2. Creates a PathGradientBrush object based on the path.
  3. Defines the brush's center color as white and its surround color as blue.
  4. Displays the path on-screen filled with the brush.

To try this code, place it in the form's Paint event procedure. The results are shown in the figure.

GraphicsPath gp1 = new GraphicsPath();
gp1.AddEllipse(20,20,380,90);
PathGradientBrush pgb = new PathGradientBrush(gp1);
pgb.CenterColor=Color.FromArgb(255,255,255,255);
Color[] colors = {Color.FromArgb(255,0,0,255)};
pgb.SurroundColors = colors;
e.Graphics.FillPath(pgb, gp1);

Drawing To A Close

In this brief article, I have been able to only scratch the surface of the power of the GraphicsPath class. I recommend that you spend some time exploring its capabilities. It's not only the graphics programmer's friend — it may be your best friend!




Discuss The GraphicsPath Class: the Graphics Programmer's Friend
 
>>> Be the FIRST to comment on this article!
 

 
 
>>> More Using VS Articles          >>> More By Peter Aitken
 



DevSource video
Devsource Video Series
Manipulating Society through Technology
Jeremy Bailenson, Director of the Virtual Human Interaction Lab at Stanford University, talks about virtual reality, avatars, Moore's law, how real world behaviors influence online reality, and societal manipulation through technology!
>> Play video
>> Read article
>> See all videos
DevLife Blog

Julia explores the Robotics Studio! (It's for more than you think.)

MSDev Blog

Messages for Bill Gates!

Make it Work
.NET makes runtime type checking a breeze. See what Peter has to say about it in this week's tips!
News
Microsoft Counts on App Support for Vista
Microsoft has taken pains to demonstrate that Windows Vista will have ample application support.
DevSource RSS FEEDS
XML Want an easy way to keep up with breaking tech news? And the Get DevSource headlines delivered to your desktop with RSS.