Paviel Kraskoŭski
Paviel Kraskoŭski

Reputation: 1419

Unstable line thickness using System.Drawing.Graphics

I'm trying to draw straight vertical lines with pen width of 1. The following method draws vertical grid lines of a line chart.

public override void DrawGridLines(GDIGraphics graphics, Rectangle plotArea)
{
    using (Pen pen = new Pen(gridLineColor, gridLineThickness))
    {
        float x = plotArea.Right - 1;
        for (int i = 0; i < niceIntervalCount; i++)
        {
            int roundedX = Mathf.RoundToInt(x);
            graphics.DrawLine(pen, roundedX, plotArea.Top, roundedX, plotArea.Bottom - 2);
            x -= niceIntervalSpacing;
        }
    }
}

gridLineThickness is set to 1. I'm passing integer parameters to DrawLine method to prevent subpixel rendering. I also disabled antialiasing and set graphics.PageUnit to GraphicsUnit.Pixel. In one cases, vertical lines are drawn with thickness of 2 (usually, when many lines).

enter image description here

In other cases, this bug disappears.

enter image description here

Click the images above to see them full size without distortion.

Upvotes: 1

Views: 568

Answers (0)

Related Questions