Draw dashed lines with different dash cap styles in C#

[dash cap]

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 Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in drawing, graphics and tagged , , , , , , , , , , , . Bookmark the permalink.

3 Responses to Draw dashed lines with different dash cap styles in C#

  1. C# lover says:

    Good post. I never thought to use Pen class to draw the shapes directly.

  2. Amy says:

    I will immediately seize your rss as I can’t in finding your email subscription link or e-newsletter service.
    Do you’ve any? Kindly let me realize so
    that I may subscribe. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *