How can I colorize a black/white UIImageView programmatically?

陌路散爱 提交于 2019-12-03 08:35:11
sahara108

You can draw new image base on this image. The below code will blends white in your image with the background color that you provide. The percent is a 0-1.0 float that controls how much of an image starting from the bottom is blended with the color you selected, so it is possible to get results like the heart filling up with red to represent hitpoints.

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

result with 0.3 percent:

The easiest way in this case would be to overlay a translucent red rectangle above the image. Since the image is black and white, the black areas will stay black. Change the height of the red rectangle to indicate different health levels.

Just make a UIView with a red background color, not opaque, the same size as the UIImageView. Set the alpha of the background color to half or less.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!