gpt4 book ai didi

iOS UIImage 剪辑到路径

转载 作者:技术小花猫 更新时间:2023-10-29 10:45:14 26 4
gpt4 key购买 nike

我正在处理一张图像,用户使用 UIBezierPath 选择了其中的一部分。我怎样才能删除/清除/透明所有不属于该选择的内容?

最佳答案

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

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

如果你想使用多条路径的并集,那就更难了,因为 Quartz 没有任何函数可以直接计算两条路径的并集。一种方法是将每条路径一条一条填充到一个mask中,然后通过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 剪辑到路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8308802/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com