Share via


How to: Draw a Custom Dashed Line

GDI+ provides several dash styles that are listed in the DashStyle enumeration. If those standard dash styles do not suit your needs, you can create a custom dash pattern.

Example

To draw a custom dashed line, put the lengths of the dashes and spaces in an array and assign the array as the value of the DashPattern property of a Pen object. The following example draws a custom dashed line based on the array {5, 2, 15, 4}. If you multiply the elements of the array by the pen width of 5, you get {25, 10, 75, 20}. The displayed dashes alternate in length between 25 and 75, and the spaces alternate in length between 10 and 20.

The following illustration shows the resulting dashed line. Note that the final dash has to be shorter than 25 units so that the line can end at (405, 5).

Pens

Dim dashValues As Single() = {5, 2, 15, 4}
Dim blackPen As New Pen(Color.Black, 5)
blackPen.DashPattern = dashValues
e.Graphics.DrawLine(blackPen, New Point(5, 5), New Point(405, 5))
float[] dashValues = { 5, 2, 15, 4 };
Pen blackPen = new Pen(Color.Black, 5);
blackPen.DashPattern = dashValues;
e.Graphics.DrawLine(blackPen, new Point(5, 5), new Point(405, 5));

Compiling the Code

Create a Windows Form and handle the form's Paint event. Paste the preceding code into the Paint event handler.

See Also

Other Resources

Using a Pen to Draw Lines and Shapes