How can I paint a black and white UIImageView programmatically?

I have a set of black and white images as shown below. If I remember correctly, there is a way to set the blending or masking property of UIImage to mix with the background UIView.

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

I know about the use of image filters, in particular, changing shades, but they are really resource-intensive, plus they do not work on a white image, so I'm looking for another solution.

Example icon

I tried overlaying a UIView with alpha 0.4 and setting its background color to red, here is 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 hue of the color that I get.

+4
source share
2 answers

You can draw a new picture on this image. The following code will mix with white in your image with the background color that you provide. Percentage is a floating 0-1.0 that controls how part of the image, starting from the bottom, mixes with your chosen color, so you can get results, such as filling the heart with red to represent hit points.

-(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 from 0.3 percent:

enter image description here

+7
source

- . -, . , .

UIView , , , UIImageView. .

0

All Articles