C# fill out side of a polygon

大兔子大兔子 提交于 2019-12-04 18:38:04

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

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