Swift 3: UIImage when set to template image and changed tint color does not show image

19,960

Solution 1

For template images the background needs to be transparent - not white.

Solution 2

Template images work by using the opacity property of an image.

If you have an image with a transparent background then the transparent background remains transparent and ALL the rest of the image is changed to the tiny colour.

If your image does not have a transparent background. Say it has a white background. Then the entire image will be changed to the tint colour (like you are seeing in your example).

To fix this you need to give that image a transparent background.

It's also worth noting that you don't need that code. If you are using an image only in template mode then just select the rendering mode in the asset catalog.

Share:
19,960
leonardloo
Author by

leonardloo

Swift ninja and machine learning enthusiast

Updated on June 29, 2022

Comments

  • leonardloo
    leonardloo almost 2 years

    In Swift 3, when I try to programmatically change the color of an image loaded from assets just like this:

    let imageView = UIImageView()
    let image = UIImage(named: "imageFromAssets")?.withRenderingMode(.alwaysTemplate)
    imageView.contentMode = .scaleAspectFit
    imageView.tintColor = GREEN_UICOLOR // Change to custom green color
    imageView.image = image
    

    The image shows up as a square block below:

    Template image with green tint that does not work

    However, the funny thing is this does not always happen. With some other images in the assets, it works and changes the tint to green:

    Template image with green tint that works

    Why is there inconsistent behavior here? And in general how do I add a template image to assets, and be able to programmatically change its color? I realize when I do not change the image to a template image it works, but I can't do that because I want to change the image's tint.