2014-09-30 96 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

相关问题