裁剪图像封闭在一个4面(不是​​矩形)的多边形

如何裁剪随机多边形内的图像部分(4面而不是矩形)。 只是想知道哪些方法不遵循代码。

您可以在Core Graphics中轻松完成此操作。

您只需创build一个新的图像上下文,添加上下文的path,然后裁剪上下文到path。 然后,您可以在此绘制图像并获取裁剪的图像。

 -(UIImage*) cropImage:(UIImage*)image withPath:(UIBezierPath*)path { // where the UIBezierPath is defined in the UIKit coordinate system (0,0) is top left CGRect r = CGPathGetBoundingBox(path.CGPath); // the rect to draw our image in (minimum rect that the path occupies). UIGraphicsBeginImageContextWithOptions(r.size, NO, image.scale); // begin image context, with transparency & the scale of the image. CGContextRef ctx = UIGraphicsGetCurrentContext(); CGContextTranslateCTM(ctx, -r.origin.x, -r.origin.y); // translate context so that when we add the path, it starts at (0,0). CGContextAddPath(ctx, path.CGPath); // add path. CGContextClip(ctx); // clip any future drawing to the path region. [image drawInRect:(CGRect){CGPointZero, image.size}]; // draw image UIImage* i = UIGraphicsGetImageFromCurrentImageContext(); // get image from context UIGraphicsEndImageContext(); // clean up and finish context return i; // return image } 

例如,如果我们截取你的问题的截图(我找不到任何其他的图片!)

在这里输入图像说明

并使用下面的代码….

 UIImage* i = [UIImage imageNamed:@"3.png"]; UIBezierPath* p = [UIBezierPath bezierPath]; [p moveToPoint:CGPointMake(0, 0)]; [p addLineToPoint:CGPointMake(1500, 500)]; [p addLineToPoint:CGPointMake(500, 1200)]; UIImage* i1 = [self cropImage:i withPath:p]; 

这将是输出…

在这里输入图像说明

如果要定期裁剪图像,甚至可以将其添加到UIImage类别。

更新了Swift 3。

我注意到有很多的实现似乎希望背景是白色或透明的,我真的只需要背景颜色是黑色的。

 extension UIImage { func crop(withPath: UIBezierPath, andColor: UIColor) -> UIImage { let r: CGRect = withPath.cgPath.boundingBox UIGraphicsBeginImageContextWithOptions(r.size, false, self.scale) if let context = UIGraphicsGetCurrentContext() { let rect = CGRect(origin: .zero, size: size) context.setFillColor(andColor.cgColor) context.fill(rect) context.translateBy(x: -r.origin.x, y: -r.origin.y) context.addPath(withPath.cgPath) context.clip() } draw(in: CGRect(origin: .zero, size: size)) guard let image = UIGraphicsGetImageFromCurrentImageContext() else { return UIImage() } UIGraphicsEndImageContext() return image } }