2014-09-30 156 views
1

我有一張圖像,裏面填充了白色邊框和黑色。我想在運行時將黑色更改爲另一種顏色。用戶將在運行時以HSB格式選擇顏色。我怎樣才能做到這一點?我試過CGImageCreateWithMaskingColors通過取 const float colorMasking [4] = {255,255,255,255}; 但是我每次都得到一個無CGImageRef。請幫忙。iOS:將UIImage中的黑色更改爲另一種顏色

- (UIImage*) maskBlackInImage :(UIImage*) image color:(UIColor*)color 
{ 
    const CGFloat colorMasking[4] = { 222, 255, 222, 255 }; 
    CGImageRef imageRef = CGImageCreateWithMaskingColors(image.CGImage, colorMasking); 
    UIImage* imageB = [UIImage imageWithCGImage:imageRef]; 
    CGImageRelease(imageRef); 
    return imageB; 

} 

我附上球的圖像 - 燈泡與黑色的色彩填滿,白色邊框,透明背景 Bulb with Black color filled, White border and transparent background

更新:

我能夠填充黑色與其他顏色在接受的答案中使用代碼後。但是,我可以在白色邊框上看到一點點顏色。圖像看起來不那麼尖銳。連接輸出:

Output - black filled with color

回答

9

創建UIImage類的類別,並添加下面的方法

- (UIImage *)imageTintedWithColor:(UIColor *)color 
{ 
    UIImage *image; 
    if (color) { 
     // Construct new image the same size as this one. 
     UIGraphicsBeginImageContextWithOptions([self size], NO, 0.0); // 0.0 for scale means "scale for device's main screen". 
     CGRect rect = CGRectZero; 
     rect.size = [self size]; 

     // tint the image 
     [self drawInRect:rect]; 
     [color set]; 
     UIRectFillUsingBlendMode(rect, kCGBlendModeScreen); 

     // restore alpha channel 
     [self drawInRect:rect blendMode:kCGBlendModeDestinationIn alpha:1.0f]; 

     image = UIGraphicsGetImageFromCurrentImageContext(); 
     UIGraphicsEndImageContext(); 
    } 
    return image; 
} 
+0

此代碼改變我唯一的白色邊框的顏色。黑色填充保持原樣。我只是想將黑色填充改爲其他顏色。 – Pria 2014-09-30 08:01:02

+0

重新創建你的圖像可能會有一些問題。您可以在預覽中打開它並重新保存。 – abhishekkharwar 2014-09-30 08:10:56

+2

混合模式是錯誤的。嘗試將kCGBlendModeMultiply更改爲kCGBlendModeScreen。我認爲這樣做。 – 2014-09-30 08:19:15

相關問題