1

我有一个带有白色边框和黑色填充的图像。我想在运行时将黑色更改为另一种颜色。用户将在运行时以 HSB 格式选择颜色。我怎样才能做到这一点?我通过 const float colorMasking [4]={255, 255, 255, 255}; 尝试了 CGImageCreateWithMaskingColors; 但我每次都得到一个 nil 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;

}

我附上了灯泡的图像 - 黑色填充、白色边框和透明背景的灯泡 黑色填充、白色边框和透明背景的灯泡

更新:

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

输出 - 黑色填充颜色

4

1 回答 1

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;
}
于 2014-09-30T07:51:59.227 回答