Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 984
leonardloo Avatar asked Jan 19 '17 07:01

leonardloo


People also ask

How do I change the UIImage color in Objective C?

extension UIImage { static func coloredImage(image: UIImage?, color: UIColor) -> UIImage? { guard let image = image else { return nil } let backgroundSize = image. size UIGraphicsBeginImageContextWithOptions(backgroundSize, false, UIScreen. main. scale) let ctx = UIGraphicsGetCurrentContext()!

How do I assign an image in Swift?

Drag and drop image onto Xcode's assets catalog. Or, click on a plus button at the very bottom of the Assets navigator view and then select “New Image Set”. After that, drag and drop an image into the newly create Image Set, placing it at appropriate 1x, 2x or 3x slot.


1 Answers

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

like image 63
Jon Rose Avatar answered Sep 18 '22 14:09

Jon Rose