I'm attempting to add a black overlay over some current UIImage's (which are white). I've been trying to use following code:
[[UIColor blackColor] set];
[image drawAtPoint:CGPointMake(0, 0) blendMode:kCGBlendModeOverlay alpha:1.0];
But it's not working, and I'm pretty sure set isn't supposed to be there.
setBlendMode(. multiply) ctx. draw(image. cgImage!, in: imageRect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } }
UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With