iOS:将UIImage中的黑色更改为其他颜色

Pri*_*ria 1 colors objective-c uiimage ios image-masking

我的图像里面有白色边框和黑色.我想在运行时将黑色更改为另一种颜色.用户将以HSB格式在运行时选择颜色.我怎样才能做到这一点?我通过采用 const float colorMasking [4] = {255,255,255,255}来尝试CGImageCreateWithMaskingColors ; 但我每次都得到一个没有CGImageRef.请帮忙.

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

}
Run Code Online (Sandbox Code Playgroud)

我附加灯泡的图像 - 灯泡与黑色填充,白色边框和透明背景 黑色填充的灯泡,白色边框和透明背景

更新:

在使用接受的答案中的代码后,我能够用另一种颜色填充黑色.但是,我可以在白色边框上看到一点颜色.图像看起来不那么尖锐.附加输出:

输出 - 黑色填充颜色

abh*_*war 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;
}
Run Code Online (Sandbox Code Playgroud)

  • 混合模式是错误的.尝试将kCGBlendModeMultiply更改为kCGBlendModeScreen.我认为会这样做. (2认同)