解决方法
有一条路很容易.只需将路径设置为剪切路径:
- (UIImage *)maskImage:(UIImage *)originalImage toPath:(UIBezierPath *)path { UIGraphicsBeginImageContextWithOptions(originalImage.size,NO,0); [path addClip]; [originalImage drawAtPoint:CGPointZero]; UIImage *maskedImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return maskedImage; }
如果要使用多个路径的并集,则更难,因为Quartz没有任何直接计算两个路径的并集的函数.一种方法是将每个路径逐个填入蒙版,然后通过掩码绘制图像:
- (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,0.0); { CGContextClipToMask(UIGraphicsGetCurrentContext(),rect,mask.CGImage); [self.originalImage drawAtPoint:CGPointZero]; } UIImage *maskedImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return maskedImage; }