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
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…