DrawEllipse: Ellipse goes outside of the Bitmap si

2019-08-27 07:05发布

I want to draw a circle with DrawEllipse on a specified Bitmap, with the same size of the Bitmap, but the result is that the circle appears clipped at the edges.
Why this problem?

Bitmap layer = new Bitmap(80, 80);
using (Graphics g = Graphics.FromImage(layer))
{
    using (Pen p = new Pen(Color.Black, 4))
    {
        g.DrawEllipse(p, new Rectangle(0, 0, layer.Width, layer.Height));
    }
}
pictureBox3.Size = new Size(100, 100);
pictureBox3.Image = layer;

drawellipse result

1条回答
地球回转人心会变
2楼-- · 2019-08-27 07:35

By default a Pen has a PenAlignment.Center.

This means that half of its widh will draw outside the bounding rectangle.

You can simply avoid the issue by changing it to PenAlignment.Inset:

using (Pen p = new Pen(Color.Black, 4) { Alignment = PenAlignment.Inset})
{
    g.DrawEllipse(p, new Rectangle(0, 0, layer.Width, layer.Height));
}

enter image description here

Update: If you want to turn on smoothing for the Graphics object you will need 1 or 2 extra pixels on both sides of the pen stroke for the anti-aliasing pixels. Using a smaller bounding rectanlge can't be avoided now. But..:

Rectangle rect = new Rectangle(Point.Empty, layer.Size);
rect.Inflate(-1, -1);  // or -2

..should do..

查看更多
登录 后发表回答