Question

Why does switching on anti-aliasing interfere with my dashed pen?

alt text
(source: googlepages.com)

Was it helpful?

Solution

I believe that this is an issue with creating a pen with a 0 width and then scaling. As I see it, there are two ways to workaround this:

  1. Create the pen with a larger width. I found that at 0.38f the dashes in the anti-aliased line started scaling properly.
  2. Manually transform the values in the Pen's DashPattern property.

You can do the latter workaround with a bit of C# 3.0 code:

protected override void OnPaint(PaintEventArgs e)
{
    Graphics g = e.Graphics;
    using (Pen p = new Pen(Color.Black, 0.0f))
    {
        p.DashStyle = DashStyle.Dash;

        g.ScaleTransform(4.0f, 4.0f);

        g.DrawLine(p, 5.0f, 5.0f, 55.0f, 5.0f);

        g.SmoothingMode = SmoothingMode.AntiAlias;
        p.DashPattern = Array.ConvertAll(p.DashPattern, d => d * 4.0f);
        g.DrawLine(p, 5.0f, 10.0f, 55.0f, 10.0f);
    }

    base.OnPaint(e);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top