Swift restore original image color after casting a tint
Asked Answered
S

2

10

I have an image, inside a UIImageView, that comes with a default color, let's say a custom grey.
In my code at some point I set a different tint in this way

myImageView.image = myImageView.image!.withRenderingMode(.alwaysTemplate)
myImageView.tintColor = someCondition() ? UIColor.red : UIColor.lightGray

The fact is that I am not able to get back to the image's original grey color. My question is if there is a way to substitute the UIColor.lightGray part of my code with something telling the UIImageView not to use any tint, but its original color.

Slim answered 12/2, 2017 at 11:28 Comment(2)
Have you tried UIColor.clear or nil?Bisexual
yep, but the both make the image transparent unfortunatelySlim
L
11

To not apply any tint you can set the image rendering mode like this:

image.renderingMode = .alwaysOriginal

In your code you could say:

let renderingMode: UIImageRenderingMode = condition ? .alwaysTemplate : .alwaysOriginal
myImageView.image = myImageView.image?.withRenderingMode(renderingMode)
Lunarian answered 12/2, 2017 at 11:41 Comment(0)
H
0

I am using this approach to change/remove tint on tap:

var imageView: UIImageView = {
    let img = UIImageView()
    img.image = someImage.withRenderingMode(.alwaysTemplate)
    img.tintColor = .cyan
    return img
}()

Add gesture recognizer to image view or button with action, and then just assign image that is already assigned to image view, but with different rendering mode:

@objc func imgTap() {
   imageView.image! = imageView.image!.withRenderingMode(.alwaysOriginal)
}
Hudnut answered 20/12, 2019 at 10:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.