Question

I'm trying to draw a lot of similar kind of lines in WPF as seen in this question, but the difference is that I need to draw it on a DrawingContext of a DrawingVisual object. How can it be done?

Was it helpful?

Solution

You would have to draw two lines between identical points on top of each other, the lower with a thicker pen, the upper with a thinner pen.

Pen background = new Pen(Brushes.Black, 5);
Pen foreground = new Pen(Brushes.White, 3);

drawingContext.DrawLine(background, new Point(100, 100), new Point(200, 200));
drawingContext.DrawLine(foreground, new Point(100, 100), new Point(200, 200));

This lines look at lot better when you also define the pen line caps:

Pen background = new Pen
{
    Brush = Brushes.Black,
    Thickness = 5,
    StartLineCap = PenLineCap.Round,
    EndLineCap = PenLineCap.Round
};

Pen foreground = new Pen
{
    Brush = Brushes.White,
    Thickness = 3,
    StartLineCap = PenLineCap.Round,
    EndLineCap = PenLineCap.Round
};

With an extension method like this

public static class DrawingContextExtensions
{
    public static void DrawLine(this DrawingContext drawingContext,
        Pen background, Pen foreground, Point start, Point end)
    {
        drawingContext.DrawLine(background, start, end);
        drawingContext.DrawLine(foreground, start, end);
    }
}

you could do the drawing in one call:

drawingContext.DrawLine(background, foreground, new Point(100, 100), new Point(200, 200));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top