I need to show a tint colored image in CALayer.
It works for UIImageView:
imageView.image = image.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
But CALayer shows the image with its original color and not the tint color.
let tintedImage = image.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
layer.contents = tintedImage.CGImage
Is there a way to show tinted image in CALayer as well?
Demo:
https://github.com/exchangegroup/calayer-with-tint-colored-image
I think my solution is far less cumbersome:
let maskLayer = CALayer()
maskLayer.frame = layer.bounds
maskLayer.contents = tintedImage.CGImage
layer.mask = maskLayer
layer.backgroundColor = UIColor.redColor().CGColor
let me know if it works fine:)
I guess that is possible on OSX using the filter property of CALayer, but in ios is not used. I think you should redraw the image totally, here is a sample code, it tints everything that has alpha > 0.
- (UIImage *)tintedImageWithColor:(UIColor *)tintColor blendingMode:(CGBlendMode)blendMode highQuality:(BOOL) yerOrNo;
{
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
if (yerOrNo) {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetShouldAntialias(context, true);
CGContextSetAllowsAntialiasing(context, true);
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
}
[tintColor setFill];
CGRect bounds = CGRectMake(0, 0, self.size.width, self.size.height);
UIRectFill(bounds);
[self drawInRect:bounds blendMode:blendMode alpha:1.0f];
if (blendMode != kCGBlendModeDestinationIn)
[self drawInRect:bounds blendMode:kCGBlendModeDestinationIn alpha:1.0];
UIImage *tintedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return tintedImage;
}
I've found this snippet on the internet but I don't remember where.
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