DrawEllipse: Ellipse goes outside of the Bitmap size

牧云@^-^@ 提交于 2019-12-13 05:07:03

问题


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;


回答1:


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));
}

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



来源:https://stackoverflow.com/questions/50574457/drawellipse-ellipse-goes-outside-of-the-bitmap-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!