Graphics paths may be useful when we need to
redraw certain graphics items. For example, suppose we have hundreds of graphics
items, including lines, rectangles, images, and text associated with a surface
but we need to redraw only the rectangles. We can create a graphics path with
all rectangles and just redraw that path, instead of the entire surface.
We may also want to use graphics paths when drawing different shapes, depending
on the complexity of the application. For example, Listing 13.11 uses draw
methods to draw two lines, two rectangles, and an ellipse. We can write code on
a button or menu click event handler.
LISTING 13.11: Drawing simple graphics objects
Imports
System.Collections.Generic
Imports
System.ComponentModel
Imports
System.Data
Imports
System.Drawing
Imports
System.Linq
Imports
System.Text
Imports
System.Windows.Forms
Public Class Form1
Private Sub Form1_Paint(ByVal
sender As System.Object,
ByVal e As
System.Windows.Forms.PaintEventArgs)
Handles MyBase.Paint
Dim g As Graphics = Me.CreateGraphics()
g.Clear(Me.BackColor)
'Create black pen
Dim blackPen
As New Pen(Color.Black,
2)
'Draw objects
g.DrawLine(blackPen, 50, 50, 200, 50)
g.DrawLine(blackPen, 50, 50, 50, 200)
g.DrawRectangle(blackPen, 60, 60, 150, 150)
g.DrawRectangle(blackPen, 70, 70, 100, 100)
g.DrawEllipse(blackPen, 90, 90, 50, 50)
'Dispose of objects
blackPen.Dispose()
g.Dispose()
End Sub
End Class
Listing 13.12 draws the same graphics objects. The only difference is that this
code uses a graphics path.
Output:

LISTING 13.12: Using a graphics path to draw graphics objects
Dim
g As Graphics
= Me.CreateGraphics()
g.Clear(Me.BackColor)
'Create a black pen
Dim blackPen
As New Pen(Color.Black,
2)
'Create a graphics path
Dim path
As New GraphicsPath()
path.Addline(50, 50, 200, 50)
path.Addline(50, 50, 50, 200)
path.AddRectangle(New Rectangle(60, 60, 150, 150))
path.AddRectangle(New Rectangle(70, 70, 100, 100))
path.Ellipse(90, 90, 50, 50)
g.DrawPath(blackPen, path)
'Dispose of objects
blackPen.Dispose()
g.Dispose()
Both Listing 13.11 and 13.12 generate the output shown in Figure 13.5. There is
no straightforward rule for when to use graphics paths. The choice depends on
the complexity of your application.
In the preceding example we saw how to replace multiple drawing statements with
a single graphics path drawing statement. But graphics paths have some
limitations. For example, we can't draw each element (line, rectangle, or an
ellipse) of a graphics path with a separate pen or brush. We have to draw or
fill them individually.
Conclusion
In this article you learned how to use graphics path in GDI+.