Hossain Muctadir
Hossain Muctadir

Reputation: 3626

Drawing multiple lines with DrawLines and DrawLine produces different result

I am trying to draw multiple lines on a winforms panel using it's graphics object in paint event. I am actually drawing a number of lines joining given points. So, first of all I did this,

    private void panel1_Paint(object sender, PaintEventArgs e)
    {
        e.Graphics.DrawLines(new Pen(new SolidBrush(Color.Crimson), 3), PointFs.ToArray());
        float width = 10;
        float height = 10;
        var circleBrush = new SolidBrush(Color.Crimson);
        foreach (var point in PointFs)
        {
            float rectangleX = point.X - width / 2;
            float rectangleY = point.Y - height / 2;
            var r = new RectangleF(rectangleX, rectangleY, width, height);

            e.Graphics.FillEllipse(circleBrush, r);
        }
    }

Which produces a result like the image below,

enter image description here

As you can see lines are drawn with having a little bit of extension at sharp turns, which is not expected. So, I changed the drawlines code to,

var pen = new Pen(new SolidBrush(Color.Crimson), 3);
for (int i = 1; i < PointFs.Count; i++)
{
    e.Graphics.DrawLine(pen, PointFs[i - 1], PointFs[i]);
}

And now the drawing works fine.

enter image description here

Can anyone tell the difference between the two approaches?

Upvotes: 0

Views: 1163

Answers (1)

Lars Lind Nilsson
Lars Lind Nilsson

Reputation: 1148

I have just had the same problem (stumbled upon this question during my research), but I have now found the solution.

The problem is caused by the LineJoin property on the Pen used. This DevX page explains the different LineJoin types (see Figure 1 for illustrations). It seems that Miter is the default type, and that causes the "overshoot" when you have sharp angles.

I solved my problem by setting the LineJoin property to Bevel:

var pen = new Pen(new SolidBrush(Color.Crimson), 3);
pen.LineJoin = Drawing2D.LineJoin.Bevel;

Now DrawLines no longer overshoot the points.

Upvotes: 1

Related Questions