objective-ccore-graphicsquartz-2d

How to use a UIImage as a mask over a color in Objective-C


I have a UIImage that is all black with an alpha channel so some parts are grayish and some parts are completely see-through. I want to use that images as a mask over some other color (let's say white to make it easy), so the final product is now a white image with parts of it transparent.

I've been looking around on the Apple documentation site here: https://developer.apple.com/library/archive/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_images/dq_images.html#//apple_ref/doc/uid/TP30001066-CH212-CJBHIJEB

But I don't can't really make sense of those examples.


Solution

  • In iOS 7+ you should use UIImageRenderingModeAlwaysTemplate instead. See https://stackoverflow.com/a/26965557/870313


    Creating arbitrarily-colored icons from a black-with-alpha master image (iOS).

    // Usage: UIImage *buttonImage = [UIImage ipMaskedImageNamed:@"UIButtonBarAction.png" color:[UIColor redColor]];
    
    + (UIImage *)ipMaskedImageNamed:(NSString *)name color:(UIColor *)color
    {
        UIImage *image = [UIImage imageNamed:name];
        CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
        UIGraphicsBeginImageContextWithOptions(rect.size, NO, image.scale);
        CGContextRef c = UIGraphicsGetCurrentContext();
        [image drawInRect:rect];
        CGContextSetFillColorWithColor(c, [color CGColor]);
        CGContextSetBlendMode(c, kCGBlendModeSourceAtop);
        CGContextFillRect(c, rect);
        UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return result;
    }
    

    Credits to Ole Zorn: https://gist.github.com/1102091