Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I colorize a black/white UIImageView programmatically?

I have a set of black and white images, like below. If I remember correctly, there's some way to set the blending or masking property of a UIImage to blend it with the background UIView.

In this case, I want to change the color of this image to red to signify hit points. How can I programmatically change the color of this UIImage?

I know about the use of image filters, in particular hue shift, but they are really resource intensive, plus they don't work on white image, so I'm looking for another solution.

Example icon

I tried overlaying a UIView with alpha 0.4 and setting it's background color to red, here's the result :

enter image description here This may work in some cases, but in my case I would like to have more control over the shade of color I'm getting.

like image 247
Alex Stone Avatar asked Mar 22 '23 06:03

Alex Stone


1 Answers

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:

enter image description here

like image 96
sahara108 Avatar answered Apr 25 '23 10:04

sahara108