如何使一个颜色在UIImage中透明

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

它的工作正常..但我想通过select颜色forms的颜色select器,然后想要使该点透明的图像上绘制一个点..我不知道如何给颜色掩盖在下面的值

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

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

从文档 :

组件

一组颜色组件,用于指定颜色或颜色范围来掩盖图像。 该数组必须包含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定义了你想要透明的每个组件的值的范围, colorMaskingcolorMasking的第一个元素是最小的红色分量,第二个元素是最大的红色分量,第三个元素是最小的绿色分量,等等。

结果图像将是一些像素透明的input图像。 哪个像素? 那些RGB值在colorMasking设置的范围之间的colorMasking

在你的例子中,数组全部为零,因为你想使黑色透明(记住,RGB中的黑色是(0,0,0))。

尝试这个-

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