iOS颜色在UIImage中透明

MB.*_*MB. 9 uiimage ios

如何清除UIImage的洋红色部分并使其透明?

我已经浏览了很多答案和SO上的链接,没有任何作用(例如,如何在UIImage上使一种颜色透明?答案1删除除红色之外的所有内容,答案2显然不起作用,因为为什么CGImageCreateWithMaskingColors()返回nil in这种情况?).

更新:

如果我使用CGImageCreateWithMaskingColors与UIImage我得到一个零值.如果我删除alpha通道(我将图像表示为JPEG并将其读回),CGImageCreateWithMaskingColors将返回涂有黑色背景的图像.

Update2,代码:

返回零:

const float colorMasking[6] = {222, 255, 222, 255, 222, 255};
CGImageRef imageRef = CGImageCreateWithMaskingColors(anchorWithMask.CGImage, colorMasking);

NSLog(@"image ref %@", imageRef);
// this is going to return a nil imgref.

UIImage *image = [UIImage imageWithCGImage:imageRef];
Run Code Online (Sandbox Code Playgroud)

返回带有黑色背景的图像(这是正常的,因为没有alpha通道):

UIImage *inputImage = [UIImage imageWithData:UIImageJPEGRepresentation(anchorWithMask, 1.0)];

const float colorMasking[6] = {222, 255, 222, 255, 222, 255};
CGImageRef imageRef = CGImageCreateWithMaskingColors(inputImage.CGImage, colorMasking);

NSLog(@"image ref %@", imageRef);
// imgref is NOT nil.

UIImage *image = [UIImage imageWithCGImage:imageRef];
Run Code Online (Sandbox Code Playgroud)

UPDATE3:

我通过在屏蔽过程之后添加alpha通道来实现它.

Art*_*eel 4

UIImage *image = [UIImage imageNamed:@"image.png"];

const float colorMasking[6] = {1.0, 1.0, 0.0, 0.0, 1.0, 1.0};
image = [UIImage imageWithCGImage: CGImageCreateWithMaskingColors(image.CGImage, colorMasking)];
Run Code Online (Sandbox Code Playgroud)

您收到 nil,因为您发送的参数无效。如果你打开苹果文档,你会看到这样的内容:

组件
颜色组件数组,指定用于遮罩图像的颜色或颜色范围。该数组必须包含 2N 个值 { min[1], max[1], ... min[N], max[N] },其中 N 是图像颜色空间中的分量数量。组件中的每个值都必须是有效的图像样本值。如果图像具有整数像素分量,则每个值必须在 [0 .. 2**bitsPerComponent - 1] 范围内(其中,bitsPerComponent 是图像的位数/分量)。如果图像具有浮点像素分量,则每个值可以是作为有效颜色分量的任何浮点数。

您可以通过按住 Option + 鼠标单击某些函数或类(例如 CGImageCreateWithMaskingColors)来快速打开文档。