如何使UIImage中的某一颜色透明

4
我希望能将UIImage中的某一颜色更改为透明色。我使用以下代码将黑色更改为透明色:
-(void)changeColorToTransparent: (UIImage *)image{
    CGImageRef rawImageRef = image.CGImage;
    const float colorMasking[6] = { 0, 0, 0, 0, 0, 0 };
    UIGraphicsBeginImageContext(image.size);
    CGImageRef maskedImageRef =  CGImageCreateWithMaskingColors(rawImageRef, colorMasking);
   {
       CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0.0, image.size.height);
       CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, -1.0);
   }

   CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, image.size.width, image.size.height), maskedImageRef);
   UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
   CGImageRelease(maskedImageRef);
   UIGraphicsEndImageContext();
 }

一切正常... 但我想通过选择颜色拾取器上的颜色,在图像上绘制一个点,然后想使该点透明... 我不知道如何在下面的代码行中给颜色掩码赋值:

const float colorMasking[6] = { 0, 0, 0, 0, 0, 0 };

请问有人能帮忙解决如何将颜色变为透明的问题吗?

2个回答

1
尝试一下这个 -
-(UIImage *)changeWhiteColorTransparent: (UIImage *)image
{
   CGImageRef rawImageRef=image.CGImage;    
   const float colorMasking[6] = {222, 255, 222, 255, 222, 255};    
   UIGraphicsBeginImageContext(image.size);
   CGImageRef maskedImageRef=CGImageCreateWithMaskingColors(rawImageRef, colorMasking);
    {
        //if in iPhone            
   CGContextTranslateCTM(UIGraphicsGetCurrentContext(), 0.0, image.size.height);
   CGContextScaleCTM(UIGraphicsGetCurrentContext(), 1.0, -1.0); 
    }

    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, image.size.width, image.size.height), maskedImageRef);
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    CGImageRelease(maskedImageRef);
    UIGraphicsEndImageContext();    
    return result;
}

1
文档中:

组件

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

如果您有一个典型的RGB图像(RGB是颜色空间的名称),则有3个组件:R(红色)、G(绿色)和B(蓝色),每个分量的取值范围为0到255(假设每个分量为8位)。
因此,colorMasking定义了您想要使其透明的每个分量的值的范围,即,colorMasking中的第一个元素是最小的红色分量,第二个元素是最大的红色分量,第三个元素是最小的绿色分量等等。
结果图像将是带有一些透明像素的输入图像。哪些像素?那些RGB值在您在colorMasking中设置的范围之间的像素。
在您的示例中,数组全部为零,因为您想要使黑色透明(请记住,在RGB中,黑色颜色为(0,0,0))。

假设我从颜色选择器中获取了一个颜色,那么我就必须得到该颜色的RGB值,假设它是100,200,150。然后在颜色掩膜中,我需要给出const float colorMasking [6] = {100, 100, 200, 200, 150, 150};,对吗? - 287986
@gtechtech 是的,那会掩盖颜色。 - Daniel Martín
感谢,它已经起作用了。我发现我们不能在掩码中使用浮点数值。 - 287986

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接