iOS UIImage剪辑到path
我正在处理用户使用UIBezierPathselect其中一部分的图像。 我如何删除/清除/透明所有不属于该select的内容?
有一条路,这很容易。 只需将path设置为剪切path:
- (UIImage *)maskImage:(UIImage *)originalImage toPath:(UIBezierPath *)path { UIGraphicsBeginImageContextWithOptions(originalImage.size, NO, 0); [path addClip]; [originalImage drawAtPoint:CGPointZero]; UIImage *maskedImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return maskedImage; }
如果你想使用多个path的联合,那就更困难了,因为Quartz没有任何直接计算两个path联合的函数。 一种方法是将每条path逐一填充到蒙版中,然后通过蒙版绘制图像:
- (UIImage *)maskedImage { CGRect rect = CGRectZero; rect.size = self.originalImage.size; UIGraphicsBeginImageContextWithOptions(rect.size, YES, 0.0); { [[UIColor blackColor] setFill]; UIRectFill(rect); [[UIColor whiteColor] setFill]; for (UIBezierPath *path in self.paths) [path fill]; } UIImage *mask = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0); { CGContextClipToMask(UIGraphicsGetCurrentContext(), rect, mask.CGImage); [self.originalImage drawAtPoint:CGPointZero]; } UIImage *maskedImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return maskedImage; }
我尝试了联合多个path的代码,它不起作用。
实际上,如果path的联合不相互重叠,我们将一条path追加到另一条path上,然后裁剪出最终的path。
UIGraphicsBeginImageContextWithOptions(originalImg.size, NO, 0); [path1 appendPath:path2]; // append path2 to path1 [path1 addClip]; [originalImg drawAtPoint:CGPointZero]; result = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();