iOS UIImage剪辑到路径 [英] iOS UIImage clip to paths

查看:127
本文介绍了iOS UIImage剪辑到路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working with an image where the user has selected part of it using UIBezierPath. How can I delete/clear out/make transparent everything that is not part of that selection?

推荐答案

只需一条路径就可以轻松实现。只需将路径设置为剪切路径:

With one path it's very easy. Just set the path as the clipping path:

- (UIImage *)maskImage:(UIImage *)originalImage toPath:(UIBezierPath *)path {
    UIGraphicsBeginImageContextWithOptions(originalImage.size, NO, 0);
    [path addClip];
    [originalImage drawAtPoint:CGPointZero];
    UIImage *maskedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return maskedImage;
}

如果你想使用多个路径的并集,那就更难了,因为Quartz没有任何直接计算两个路径的并集的函数。一种方法是逐个填充每个路径到一个掩码,然后通过掩码绘制图像:

If you want to use the union of multiple paths, it's harder, because Quartz doesn't have any functions that directly compute the union of two paths. One way is to fill each path one by one into a mask, and then draw the image through the mask:

- (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;
}

这篇关于iOS UIImage剪辑到路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆