[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 custom dash patterns in C#

[Draw lines with custom dash patterns in C#]

To create lines with custom dash patterns, first create a Pen object and set its DashStyle property to Custom. Then set its DashPattern property to an array of floating point numbers that indicate how many units to draw and then skip. For example, the array { 5, 1 } means draw 5, skip 1, and then repeat as needed.

The drawing unit is the thickness of the line. For example, if the line is 5 pixels wide, then the array { 5, 1 } means draw 5 × 5 = 25 pixels, skip 1 × 5 = 5 pixels, and repeat.

The example program uses the following code to draw its samples.

private void Form1_Paint(object sender, PaintEventArgs e) { int y = 20; int x1 = 65; int x2 = ClientSize.Width - 10; using (Pen dashed_pen = new Pen(Brushes.Red, 5)) { dashed_pen.DashStyle = DashStyle.Custom; dashed_pen.DashPattern = new float[] { 3, 1 }; e.Graphics.DrawString("3, 1", this.Font, Brushes.Black, 10, y - 8); e.Graphics.DrawLine(dashed_pen, x1, y, x2, y); y += 20; dashed_pen.DashPattern = new float[] { 5, 1, 5, 5 }; e.Graphics.DrawString("5, 1, 5, 5", this.Font, Brushes.Black, 10, y - 8); e.Graphics.DrawLine(dashed_pen, x1, y, x2, y); y += 20; dashed_pen.DashPattern = new float[] { 5, 1 }; e.Graphics.DrawString("5, 1", this.Font, Brushes.Black, 10, y - 8); e.Graphics.DrawLine(dashed_pen, x1, y, x2, y); y += 20; dashed_pen.DashPattern = new float[] { 1, 3 }; e.Graphics.DrawString("1, 3", this.Font, Brushes.Black, 10, y - 8); e.Graphics.DrawLine(dashed_pen, x1, y, x2, y); y += 20; dashed_pen.DashPattern = new float[] { 3, 1, 1, 1 }; e.Graphics.DrawString("3, 1, 1, 1", this.Font, Brushes.Black, 10, y - 8); e.Graphics.DrawLine(dashed_pen, x1, y, x2, y); y += 20; } }

Don't forget to use the Pen'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.