We have already seen how to use the StartCap and EndCap properties of a Pen
object to set the starting and ending caps of lines. We have also seen how to
use the StartCustomCap and EndCustomCap properties to set customized starting
and ending caps.
FIGURE 9.12: The Round line join effect
FIGURE 9.13: Customized starting and ending caps
To understand caps better, take a look at Figure 9.13. The rectangle A is a line
cap. The starting cap is triangular and the ending cap is round.
The GetStrokeCaps and SetStrokeCaps methods of the CustomLineCap class can also
be used to get and set the starting and ending caps of a custom cap. The
SetStrokeCaps method takes two arguments of type LineCap enumeration and sets
the caps for the starting and ending points of lines. Listing 9.7 creates custom
line caps and sets them using the SetStrokeCaps methods. After creating custom
line caps, we create a pen and set its CustomStartCap and CustomEndCap
properties, which use the pen to draw a line.
LISTING 9.7: Using SetStrokeCaps
{
// Create a Graphics object
Graphics g =
this.CreateGraphics();
g.Clear(this.BackColor);
// Create a path for custom line cap. This
path will have two line from points
// (-3, -3) to (0, 0) and (0, 0) to
(3, -3).
Point[] points =
{
new
Point (-3, -3),
new
Point (0,0),
new
Point (3, -3)
};
GraphicsPath path = new GraphicsPath();
path.AddLines(points);
// Create a custom line cap from the path
CustomLineCap cap = new
CustomLineCap(null, path);
// Set the starting and ending caps of the
custom cap
cap.SetStrokeCaps(LineCap.Round, LineCap.Triangle);
// Create a Pen object and set its
starting and ending caps
Pen redPen =
new Pen(Color.Red,
15);
redPen.CustomStartCap = cap;
redPen.CustomEndCap = cap;
redPen.DashStyle = DashStyle.DashDotDot;
// Draw the line
g.DrawLine(redPen,
new
Point(100, 100),
new
Point(400, 100));
// Dispose of objects
g.Dispose();
}