DrawEllipse: Ellipse goes outside of the Bitmap size

470 views Asked by At

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

There are 1 answers

3
TaW On BEST ANSWER

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..