C# fill out side of a polygon

半城伤御伤魂 提交于 2019-12-06 13:17:25

问题


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.


回答1:


You can do this by using a GraphicsPath as follows:

  1. Add the polygon to the path.
  2. Add a rectangle to the path which encompasses the area you want to "invert".
  3. 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).



来源:https://stackoverflow.com/questions/43185020/c-sharp-fill-out-side-of-a-polygon

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