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

任何人都可以帮助我如何使颜色变为透明

4

2 回答 2

1

文档

成分

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

简单来说,如果你有一个典型的 RGB 图像(RGB 是颜色空间的名称),那么你有 3 个分量:R(红色)、G(绿色)和 B(蓝色),每个分量的范围从 0 到255(2**8 - 1,假设每个组件 8 位)。

因此,colorMasking定义您想要透明的每个组件的值范围,即,第一个元素colorMasking是最小的红色组件,第二个是最大的红色组件,第三个是最小的绿色组件,等等向前。

结果图像将是具有一些透明像素的输入图像。哪个像素?那些 RGB 值介于您设置的范围之间的人colorMasking

在您的示例中,数组全为零,因为您想让黑色透明(请记住,RGB 中的黑色为 (0,0,0))。

于 2013-10-18T07:04:55.420 回答
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;
}
于 2013-10-18T07:08:34.367 回答