views:

73

answers:

1

I've been seeing some odd behaviour with fractional pen widths, and I wonder if anyone can explain what's going on. Drawing a rectangle on a form in response to a Paint event:

private void Form1_Paint(object sender, PaintEventArgs e)
{
  const float width = 1.996093F;
  Rectangle rectangle = new Rectangle(10, 10, 20, 20);

  using (Pen pen = new Pen(Color.Black, width))
  {
    e.Graphics.DrawRectangle(pen, rectangle);
  }
}

With width between 0 and 1.996093, I get a 1-pixel-wide rectangle. With width between 1.996094 and 2.003906, I get a 2-pixel-wide rectangle; from 2.003907 to 3.996093 I get 3 pixels, and so on. Even more bizarrely, with a width of 1.9960937, I get a rectangle that is two pixels wide on its top edge, and one pixel wide on its other edges.

Can anyone explain what's happening here? I was kind of hoping that the cutoff points would be 1.5, 2.5, 3.5, etc.

A: 

You should see the issue going away when you enable anti-aliasing for the Graphics object you're drawing on, I think.

The problem is an eternal one: When you got partially drawn pixels, will they be black or white? The result depends on the algorithm and guessing.

Though I wonder why you are using fractional pixel widths at all when you actually want crisp and clear one- or two-pixel wide lines. You can easily round your widths to integers and shouldn't see any issues like that anymore.

Joey