C#填充多边形的一侧 [英] C# fill out side of a polygon
问题描述
在c#中,我可以在位图图像中填充多边形,如下所示。
使用(Graphics g = Graphics.FromImage(bitmap))
{
g.FillPolygon(colorBrush ,points.ToArray());
}
FillPolygon
方法填充多边形内的像素,在这种情况下,白色像素和黑色像素保持不变。 / p>
现在,我想要与此操作相反。这意味着,外部像素将被填充,内部像素将保持不变。在这种情况下,黑色像素是外部像素。
编辑
我需要这个,因为我要说,我有一个二进制图像一个东西。我需要用背景颜色(黑色)剪切像素,白色多边形内的像素将保持不变。
你可以通过使用 GraphicsPath
执行此操作,如下所示:
- 将多边形添加到路径。
- 在路径中添加一个矩形,该路径包含您要反转的区域。
- 使用
Graphics.FillPath ()
来填充路径。
对于示例程序,创建一个默认的Windows窗体应用程序并覆盖 OnPaint()
如下:
protected override void OnPaint(PaintEventArgs e )
{
base.OnPaint(e);
var points = new []
{
新PointF(150,250),
新PointF(50,500),
新PointF( 250,400),
新PointF(300,100),
新PointF(500,500),
新PointF(500,50),
};
使用(var path = new GraphicsPath())
{
path.AddPolygon(points);
//取消注释以反转:
// p.AddRectangle(this.ClientRectangle);
使用(var brush = new SolidBrush(Color.Black))
{
e.Graphics.FillPath(brush,path);
}
}
}
如果你运行(和调整窗口大小)你会在白色窗口内看到一个黑色的形状。
取消注释指示的行并运行程序,你会在黑色中看到一个白色的形状窗口(即添加 ClientRectangle
将其反转)。
In c# I can fill a polygon in a bitmap image as following.
using (Graphics g = Graphics.FromImage(bitmap))
{
g.FillPolygon(colorBrush, points.ToArray());
}
FillPolygon
method fills the pixels inside the polygon, in this case, the white pixels and the black pixels remains the same.
Now, I want just the opposite of this operation. That means, exterior pixels will be filled and interior pixels will remain the same. I this case, black pixels are exterior pixels.
Edit I need this because let's say, I have a binary image of an object. I need to clip the pixels with background color(black) and the pixels inside the white polygon will remain unchanged.
You can do this by using a GraphicsPath
as follows:
- Add the polygon to the path.
- Add a rectangle to the path which encompasses the area you want to "invert".
- Use
Graphics.FillPath()
to fill the path.
For an example program, create a default Windows Forms app and override OnPaint()
as follows:
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
var points = new []
{
new PointF(150, 250),
new PointF( 50, 500),
new PointF(250, 400),
new PointF(300, 100),
new PointF(500, 500),
new PointF(500, 50),
};
using (var path = new GraphicsPath())
{
path.AddPolygon(points);
// Uncomment this to invert:
// p.AddRectangle(this.ClientRectangle);
using (var brush = new SolidBrush(Color.Black))
{
e.Graphics.FillPath(brush, path);
}
}
}
If you run that (and resize the window) you'll see a black shape inside a white window.
Uncomment the indicated line and run the program and you'll see a white shape inside a black window (i.e. adding the ClientRectangle
inverted it).
这篇关于C#填充多边形的一侧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!