Draw lines with end caps in C#

[end caps]

The Pen class’s StartCap and EndCap properties determine how a line draws its end caps. This example uses the following code to draw samples of the predefined end caps.

private void Form1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.Clear(BackColor);
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;

    const int line_width = 10;
    int y = 10;
    int x1 = 110;
    int x2 = ClientSize.Width - 2 * line_width;
    using (Pen pen = new Pen(Color.Blue, line_width))
    {
        LineCap[] caps = (LineCap[])Enum.GetValues(typeof(LineCap));
        foreach (LineCap cap in caps)
        {
            e.Graphics.DrawString(cap.ToString(),
                Font, Brushes.Black, 10, y);
            pen.StartCap = cap;
            pen.EndCap = cap;
            e.Graphics.DrawLine(pen, x1, y, x2, y);
            y += 2 * line_width;
        }
    }
}

After some preliminaries, the code uses Enum.GetValues to get an array containing the values defined by the LineCap enumeration. It then loops through those values.

For each value, the code sets a Pen object’s StartCap and EndCap properties to the value. It then draws the name of the LineCap value and uses the Pen to draw the sample.

Most the the end caps are straightforward, but a few have special meaning. NoAnchor makes the line not include an end cap. AnchorMask specifies a mask used to determine whether the line cap is an anchor cap. I don’t know why you would need to do that.

Custom lets you define a custom end cap. I’ll show how to use it in my next post.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in drawing, graphics and tagged , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

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