[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Draw lines with end caps in C#

[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.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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.