How can I set the color of a templated image that is an attachment on an attributed string?
Background:
I\'ve got a UILabel and I\'m setting its attributedTe
I have good experience with using the library UIImage+Additions when tinting UIImage
instances. Specially check section IV.
If adding a third-party library is not an option, here is something to get you started:
- (UIImage *)colorImage:(UIImage *)image color:(UIColor *)color
{
UIGraphicsBeginImageContextWithOptions(image.size, NO, [UIScreen mainScreen].scale);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0, image.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
CGContextSetBlendMode(context, kCGBlendModeNormal);
CGContextDrawImage(context, rect, image.CGImage);
CGContextSetBlendMode(context, kCGBlendModeSourceIn);
[color setFill];
CGContextFillRect(context, rect);
UIImage *coloredImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return coloredImage;
}
This will make a UIImage
go from:
To
Update: Swift version:
extension UIImage {
func colorImage(with color: UIColor) -> UIImage? {
guard let cgImage = self.cgImage else { return nil }
UIGraphicsBeginImageContext(self.size)
let contextRef = UIGraphicsGetCurrentContext()
contextRef?.translateBy(x: 0, y: self.size.height)
contextRef?.scaleBy(x: 1.0, y: -1.0)
let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
contextRef?.setBlendMode(CGBlendMode.normal)
contextRef?.draw(cgImage, in: rect)
contextRef?.setBlendMode(CGBlendMode.sourceIn)
color.setFill()
contextRef?.fill(rect)
let coloredImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return coloredImage
}
}