Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show tint colored image in CALayer on iOS?

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

enter image description here

like image 425
Evgenii Avatar asked Nov 17 '14 22:11

Evgenii


2 Answers

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:)

like image 55
J.Williams Avatar answered Sep 21 '22 13:09

J.Williams


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.

like image 23
Andrea Avatar answered Sep 20 '22 13:09

Andrea