iOS UIImage剪辑到路径

时间:2011-11-29 09:54:53

标签: ios uiimage

我正在处理用户使用UIBezierPath选择部分图像的图像。如何删除/清除/透明不属于该选择的所有内容?

2 个答案:

答案 0 :(得分:20)

有一条路很容易。只需将路径设置为剪切路径:

- (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, NO, 0.0); {
        CGContextClipToMask(UIGraphicsGetCurrentContext(), rect, mask.CGImage);
        [self.originalImage drawAtPoint:CGPointZero];
    }
    UIImage *maskedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return maskedImage;
}

答案 1 :(得分:0)

我尝试了多个路径的联合代码,但它不起作用。

实际上,如果路径的并集彼此不重叠,我们会将一条路径附加到另一条路径并使用最终路径进行裁剪。

UIGraphicsBeginImageContextWithOptions(originalImg.size, NO, 0);
[path1 appendPath:path2]; // append path2 to path1
[path1 addClip];

[originalImg drawAtPoint:CGPointZero];
result = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();