Render dashed lines in a WPF program using C#

[Render dashed lines]

When you draw in WPF, you create a Pen object. You can set that object’s DashStyle to make the pen draw dashed or dotted lines. The following code shows how this example draws the second line from the top.


Pen dashed_pen = new Pen(Brushes.Blue, line_thickness);
dashed_pen.DashStyle = DashStyles.Dash;
drawingContext.DrawLine(dashed_pen, point1, point2);

The DashStyles enumeration defines the styles Dash, DashDot, DashDotDot, Dot, and Solid.

Sometimes you may want to define your own dash styles. For example, in a dashed line with a thickness of one pixel, the dashes are very small and the spaces between them are even smaller. After WPF finishes anti-aliasing the Dot style to make things look smoother, the result appears to be a fuzzy but solid line that doesn’t seem to have any breaks in it.

In those cases, you may want to use a custom dash style. For example, skipping 5 pixels and then drawing 5 pixels produces a nice easy-to-see dash style for a thin line.

The following code shows how the program creates its first custom line (the one drawn in green).

Pen custom1_pen = new Pen(Brushes.Green, line_thickness);
DashStyle dash_style1 = new DashStyle(
    new double[] { 5, 5 }, 0);
custom1_pen.DashStyle = dash_style1;
drawingContext.DrawLine(custom1_pen, point1, point2);

This code creates a green Pen. It then makes a new DashStyle object, passing its constructor an array of doubles that defines the dash pattern. The values in the array indicate the distance drawn and then skipped as multiples of the line’s thickness. The values are adjusted by the dash cap at the ends of each dash, so the dashes tend to get a bit of extra length and the gaps between them shrink a bit. When WPF anti-aliases the result to make it smoother, it also makes the edges of the dashes a bit fuzzy, so the sizes won’t be exactly what you specify.

The following code shows how the example creates its last custom dash pattern.

Pen custom3_pen = new Pen(Brushes.Green, line_thickness);
DashStyle dash_style3 = new DashStyle(
    new double[] { 3, 2, 3, 2, 0, 2 }, 0);
custom3_pen.DashStyle = dash_style3;
drawingContext.DrawLine(custom3_pen, point1, point2);

This is similar to the previous code except it specifies a longer sequence of dashes and gaps to make a dash-dash-dot pattern.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in drawing, geometry, graphics, wpf, XAML and tagged , , , , , , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *