2011-11-29 73 views
9

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

我查看了很多答案和链接,所以没有任何作品(例如How to make one color transparent on a UIImage?答案1删除一切,但红色,答案2显然不工作,因为Why is CGImageCreateWithMaskingColors() returning nil in this case?)。

更新:

如果我使用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]; 

返回与黑色背景的图像(这是正常的,因为没有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]; 

Update3:

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

+2

发布您的代码。 –

+2

添加了代码。 –

回答

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)]; 

您收到零,因为您发送的参数无效。如果你打开苹果的文件,你会看到:

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

您可以通过按住Option +鼠标快速打开文档点击一些功能或类,如CGImageCreateWithMaskingColors。

+0

我刚试过这个,它返回一个完全透明的图像。 –

+0

这就是输入图像的样子:http://i.imgur.com/lxJdm.png(这是png版本,内部是UIImagePicker的UIImage) –

4

我做了这个静态函数,消除白色背景,你可以用它来与您要删除的颜色范围更换面膜:

+ (UIImage*) processImage :(UIImage*) image 
{ 
    const float colorMasking[6]={222,255,222,255,222,255}; 
    CGImageRef imageRef = CGImageCreateWithMaskingColors(image.CGImage, colorMasking); 
    UIImage* imageB = [UIImage imageWithCGImage:imageRef]; 
    CGImageRelease(imageRef); 
    return imageB; 
} 
+1

我在测试之前投了票,它没有测试它,工作。 –

+0

它正在处理我的项目,我正在删除白色的颜色范围。我想你可以指定颜色范围,就像我在222 - > 255中使用的红色一样。我可能不会100%理解它,但是您可以在需要的范围内再次尝试。 –

+0

@khaledannajar我已经使用这个代码它的工作完美,但仍然有些白色pixcel不能删除空白行的边界,我已经在我的应用程序中编程式绘制 – kb920