Title: Draw dashed lines with different dash cap styles in C#
A dash cap determines how the program draws the ends of the dots and dashes that make up a dashed line. If the line is 1 pixel wide, you probably won't notice any difference, but dash caps are easy to see on thick lines.
To change a line's dash caps, create a Pen to draw a dashed line and then set its DashCap property to the style you want. The following code shows how this example draws its dashed lines.
using (Pen dashed_pen = new Pen(Color.Green, 15))
{
dashed_pen.DashStyle = DashStyle.Dash;
dashed_pen.DashCap = DashCap.Flat;
e.Graphics.DrawString("Flat", this.Font,
Brushes.Black, 10, y - 8);
e.Graphics.DrawLine(dashed_pen, 100, y, 250, y);
y += 20;
dashed_pen.DashCap = DashCap.Round;
e.Graphics.DrawString("Round", this.Font,
Brushes.Black, 10, y - 8);
e.Graphics.DrawLine(dashed_pen, 100, y, 250, y);
y += 20;
dashed_pen.DashCap = DashCap.Triangle;
e.Graphics.DrawString("Triangle", this.Font,
Brushes.Black, 10, y - 8);
e.Graphics.DrawLine(dashed_pen, 100, y, 250, y);
y += 20;
}
This code creates a 15 pixel wide Pen and sets its DashStyle property to make it draw a dashed line. It then uses it to draw three lines with different DashCap values.
Don't forget to use the Pen object's Dispose method to free graphics resources. If you use the using statement as in this example, C# calls Dispose automatically for you.
Download the example to experiment with it and to see additional details.
|