Search code examples
iosuiimagecalayer

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


Solution

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