Overlaying a UIImage with a color?
You will want to clip the context to an image mask and then fill with a solid color:
- (void)drawRect:(CGRect)rect
{
CGRect bounds = [self bounds];
[[UIColor blackColor] set];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextClipToMask(context, bounds, [myImage CGImage]);
CGContextFillRect(context, bounds);
}
Note: myImage
should be an instance variable that contains an UIImage
. I'm not sure whether it takes the mask from the alpha channel or the intensity so try both.
So, to sum up all the answers into one here's the drop-in method that works perfectly from iOS 6
all the way up to iOS 11
with all kinds of images and icons:
+ (UIImage *)filledImageFrom:(UIImage *)source withColor:(UIColor *)color{
// begin a new image context, to draw our colored image onto with the right scale
UIGraphicsBeginImageContextWithOptions(source.size, NO, [UIScreen mainScreen].scale);
// get a reference to that context we created
CGContextRef context = UIGraphicsGetCurrentContext();
// set the fill color
[color setFill];
// translate/flip the graphics context (for transforming from CG* coords to UI* coords
CGContextTranslateCTM(context, 0, source.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetBlendMode(context, kCGBlendModeColorBurn);
CGRect rect = CGRectMake(0, 0, source.size.width, source.size.height);
CGContextDrawImage(context, rect, source.CGImage);
CGContextSetBlendMode(context, kCGBlendModeSourceIn);
CGContextAddRect(context, rect);
CGContextDrawPath(context,kCGPathFill);
// generate a new UIImage from the graphics context we drew onto
UIImage *coloredImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//return the color-burned image
return coloredImg;
}
Update: Swift 3 version
func filledImage(source: UIImage, fillColor: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(source.size, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()
fillColor.setFill()
context!.translateBy(x: 0, y: source.size.height)
context!.scaleBy(x: 1.0, y: -1.0)
context!.setBlendMode(CGBlendMode.colorBurn)
let rect = CGRect(x: 0, y: 0, width: source.size.width, height: source.size.height)
context!.draw(source.cgImage!, in: rect)
context!.setBlendMode(CGBlendMode.sourceIn)
context!.addRect(rect)
context!.drawPath(using: CGPathDrawingMode.fill)
let coloredImg : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return coloredImg
}