[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 dashed lines in C#

[Draw dashed lines in C#]

To draw dashed lines, create a new Pen and set its DashStyle property to indicate the dash style you want. For example, the following code draws two dashed lines, one with the style Dash and one with the style DashDot.

using (Pen dashed_pen = new Pen(Color.Blue, 2)) { ... dashed_pen.DashStyle = DashStyle.Dash; e.Graphics.DrawString("Dash", this.Font, Brushes.Black, 10, y - 8); e.Graphics.DrawLine(dashed_pen, 100, y, 250, y); y += 20; dashed_pen.DashStyle = DashStyle.DashDot; e.Graphics.DrawString("DashDot", this.Font, Brushes.Black, 10, y - 8); e.Graphics.DrawLine(dashed_pen, 100, y, 250, y); y += 20; ... }

Note that the size of the gaps in dashed lines depends on the line's width. If a line is 10 pixels wide, then the gap between dashes is 10 pixels long. Dots are the same length as the gaps and dashes are twice as long.

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.

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