如何以编程方式为黑/白UIImageView着色?

Ale*_*one 4 iphone mask colors objective-c uiimage

我有一组黑白图像,如下所示.如果我没记错的话,可以通过某种方式设置UIImage的混合或遮罩属性,将其与背景UIView混合.

在这种情况下,我想将此图像的颜色更改为红色以表示生命值.如何以编程方式更改此UIImage的颜色?

我知道图像滤镜的使用,特别是色调偏移,但它们真的是资源密集型,而且它们不适用于白色图像,所以我正在寻找另一种解决方案.

示例图标

我尝试用alpha 0.4覆盖UIView并将其背景颜色设置为红色,这是结果:

在此输入图像描述 这可能在某些情况下有效,但在我的情况下,我希望能够更好地控制我所获得的颜色.

sah*_*108 7

您可以在此图像上绘制新图像.以下代码会将图像中的白色与您提供的背景颜色混合.百分比是0-1.0浮点数,用于控制从底部开始的图像与您选择的颜色混合的程度,因此可以获得像心脏填充红色的结果来表示生命值.

-(UIImage*)blendImage:(UIImage*)image withColor:(UIColor*)color fillUpTo:(float)percent
{
    //math got me
    float realPercent = 1.0-percent;

    CGSize size = image.size;
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, CGRectMake(0, size.height*realPercent, size.width, size.height*(1-realPercent)));

    //make sure the image is not upside down
    CGContextTranslateCTM(context, 0, image.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    //draw image by blending colors
    CGContextSetBlendMode(context, kCGBlendModeMultiply);
    CGContextDrawImage(context, CGRectMake(0, 0, size.width, size.height), image.CGImage);


    UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return resultImage;
}
Run Code Online (Sandbox Code Playgroud)

结果为0.3%:

在此输入图像描述