2011-11-29 70 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