【问题标题】:How to make one colour transparent in UIImage如何在 UIImage 中使一种颜色透明
【发布时间】:2013-10-18 06:49:12
【问题描述】:

我想将 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 };

谁能帮我把颜色变成透明

【问题讨论】:

    标签: ios objective-c uiimage uicolor


    【解决方案1】:

    来自docs

    组件

    指定颜色或颜色范围的颜色组件数组 来掩盖图像。数组必须包含 2N 个值 { min1, max1, ... 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))。

    【讨论】:

    • 所以假设如果从 ColourPicker 获得一种颜色,那么我必须获得该颜色的 RBG 假设它是 100,200,150 然后在颜色遮罩中我必须给出 const float colorMasking[6] = { 100, 100, 200, 200, 150, 150 };对吗?
    • @gtechtech 是的,这会掩盖颜色。
    • 感谢丢失了它的工作。我发现我们不能在掩码中使用浮点值
    【解决方案2】:

    试试这个-

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

    【讨论】:

      猜你喜欢
      • 2010-10-12
      • 1970-01-01
      • 2016-05-30
      • 2012-05-03
      • 1970-01-01
      • 2012-03-16
      • 2012-07-04
      • 1970-01-01
      • 2012-04-22
      相关资源
      最近更新 更多