Sumsuddin Shojib
Sumsuddin Shojib

Reputation: 3743

C# fill out side of a polygon

In c# I can fill a polygon in a bitmap image as following.

        using (Graphics g = Graphics.FromImage(bitmap))
        {
            g.FillPolygon(colorBrush, points.ToArray());
        }

After Using FillPolygon()

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.

Upvotes: 1

Views: 1837

Answers (1)

Matthew Watson
Matthew Watson

Reputation: 109732

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

Upvotes: 1

Related Questions