如何在WinForm pictureBox中从图像中裁剪一个多边形区域?

10

我怎样可以使用多边形截取图片的一部分?例如,我有6个坐标点,想要切割图片的这一部分。

enter image description here


https://github.com/dlemstra/Magick.NET - Gerhard
1个回答

12
你可以将List中的Points转换成多边形形状,再转换为GraphicsPath,然后转换为Region,并在调用Graphics.Clip(Region)之后使用Graphics.DrawImage方法即可完成。
using System.Drawing.Drawing2D;

GraphicsPath gp = new GraphicsPath();   // a Graphicspath
gp.AddPolygon(points.ToArray());        // with one Polygon

Bitmap bmp1 = new Bitmap(555,555);  // ..some new Bitmap
                                    // and some old one..:
using (Bitmap bmp0 = (Bitmap)Bitmap.FromFile("D:\\test_xxx.png"))
using (Graphics G = Graphics.FromImage(bmp1))
{
    G.Clip = new Region(gp);   // restrict drawing region
    G.DrawImage(bmp0, 0, 0);   // draw clipped
    pictureBox1.Image = bmp1;  // show maybe in a PictureBox
}
gp.Dispose();  

请注意,您可以自由选择DrawImage位置的任何地方,包括在原点左侧和顶部的负区域。

另外请注意,对于“真正的”裁剪,您的一些(至少4个)点应该命中目标Bitmap的边界!或者您可以使用GraphicsPath来获取其边界框:

RectangleF rect = gp.GetBounds();
Bitmap bmp1 = new Bitmap((int)Math.Round(rect.Width, 0), 
                         (int)Math.Round(rect.Height,0));
..

但是矩形只有4条边,这不是一个问题吗? - Eminem
边界框不是用于裁剪而是用于确定目标位图大小的最小目标矩形。对于裁剪,需要使用graphicspath和clip。使用graphicspath的边界是一种方便的方法,而不是分析所有这些点。 - TaW
一开始没起作用 - 必须调整剪辑坐标为基于零的。 - A X

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接