如何从 WinForm pictureBox 中的图像裁剪多边形区域? [英] How to crop a polygonal area from an image in a WinForm pictureBox?
问题描述
如何用多边形裁剪图像的一部分?例如,我有 6 个坐标,我想剪切图像的这一部分.
How can I crop a part of an image with a polygon? For example I have 6 coordinates and I would like to cut this part of an image.
推荐答案
可以将Points
的List
做成Polygon,再做成GraphicsPath
然后进入 Region
和 Graphics.Clip(Region)
之后,你可以 Graphics.DrawImage
并完成..:>
You can make the List
of Points
into a Polygon, then into a GraphicsPath
and then into a Region
and after Graphics.Clip(Region)
you can Graphics.DrawImage
and are done..:
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
位置,包括在原点左侧和顶部的负区域..
Note that you are free to choose the DrawImage
location anywhere, including in the negative area to the left and top of the origin..
另请注意,对于真实"裁剪,您的一些(至少 4 个)点应该击中目标 Bitmap
的边界!- 或者您可以使用 GraphicsPath
获取其边界框:
Also note that for 'real' cropping some (at least 4) of your points should hit the target Bitmap
's borders! - Or you can use the GraphicsPath
to get its bounding box:
RectangleF rect = gp.GetBounds();
Bitmap bmp1 = new Bitmap((int)Math.Round(rect.Width, 0),
(int)Math.Round(rect.Height,0));
..
这篇关于如何从 WinForm pictureBox 中的图像裁剪多边形区域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!