C# System.Drawing.Rectangle 到 System.Drawing.Bitmap 上的椭圆
C# System.Drawing.Rectangle into Ellipse on System.Drawing.Bitmap
我有一个面部识别库在工作,它为我提供了一个矩形数组。现在我正在用这种方式绘制矩形。
foreach (Rectangle box in boxes)
{
for (int x = box.X; x <= box.X + box.Width; x++)
{
for (int y = box.Y; y <= box.Y + box.Height; y++)
{
outputbmp.SetPixel(x, y, Color.FromKnownColor(KnownColor.Red));
}
}
}
我正在寻找像这样简单的东西:
Ellipse ellipse = new Ellipse(box); //cast rect to ellipse
outputbmp.DrawEllipse(ellipse);
看起来更像:
椭圆的轮廓与矩形角接触的位置。
根据我上面使用的方法,绘制矩形很容易,但是对于椭圆,它需要我知道椭圆中的所有点。只是想知道是否有什么可以让我的生活更轻松。
不要尝试直接在位图上绘图,您可以创建一个更高级别的对象,称为 Graphics,它为您提供各种精彩的绘图工具。它也比逐像素绘制快得多。
您可以通过调用 Graphics.FromImage
并传入位图为给定的 Bitmap
创建 Graphics
。你必须记住在 Graphics 上调用 Dispose
,否则它会泄漏资源。
一旦您的位图有了 Graphics
实例,您就可以调用 DrawEllipse
并完全按照您的预期传入边界。
来自MSDN:
private void DrawEllipseInt(Graphics g)
{
// Create pen.
Pen blackPen = new Pen(Color.Black, 3);
// Create location and size of ellipse.
int x = 0;
int y = 0;
int width = 200;
int height = 100;
// Draw ellipse to screen.
g.DrawEllipse(blackPen, x, y, width, height);
}
我有一个面部识别库在工作,它为我提供了一个矩形数组。现在我正在用这种方式绘制矩形。
foreach (Rectangle box in boxes)
{
for (int x = box.X; x <= box.X + box.Width; x++)
{
for (int y = box.Y; y <= box.Y + box.Height; y++)
{
outputbmp.SetPixel(x, y, Color.FromKnownColor(KnownColor.Red));
}
}
}
我正在寻找像这样简单的东西:
Ellipse ellipse = new Ellipse(box); //cast rect to ellipse
outputbmp.DrawEllipse(ellipse);
看起来更像:
椭圆的轮廓与矩形角接触的位置。
根据我上面使用的方法,绘制矩形很容易,但是对于椭圆,它需要我知道椭圆中的所有点。只是想知道是否有什么可以让我的生活更轻松。
不要尝试直接在位图上绘图,您可以创建一个更高级别的对象,称为 Graphics,它为您提供各种精彩的绘图工具。它也比逐像素绘制快得多。
您可以通过调用 Graphics.FromImage
并传入位图为给定的 Bitmap
创建 Graphics
。你必须记住在 Graphics 上调用 Dispose
,否则它会泄漏资源。
一旦您的位图有了 Graphics
实例,您就可以调用 DrawEllipse
并完全按照您的预期传入边界。
来自MSDN:
private void DrawEllipseInt(Graphics g)
{
// Create pen.
Pen blackPen = new Pen(Color.Black, 3);
// Create location and size of ellipse.
int x = 0;
int y = 0;
int width = 200;
int height = 100;
// Draw ellipse to screen.
g.DrawEllipse(blackPen, x, y, width, height);
}