Title: Draw lines with end caps in C#
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.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)
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 the example to experiment with it and to see additional details.