iOS Swift programmatically change Image Tint Color

We will take help of the method withRenderingMode for this. This method creates and returns a new image object with the specified rendering mode. The specific mode that we will use here is UIImage.RenderingMode.alwaysTemplate which will draw the image as a template image, ignoring its color information. Then we can just color it with whatever.

iOS Swift programmatically change Image Tint Color

iOS Swift create new UIImage with a different color

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationItem.title = "Main View"
        
        //Original image displayed as is
        let imageView = UIImageView()
        imageView.frame = CGRect(x: 50, y: 50, width: 200, height: 200)
        imageView.contentMode = .scaleAspectFit
        view.addSubview(imageView)
        
        let myImageName = "apple_logo.png"
        let myImage = UIImage(named: myImageName)
        imageView.image = myImage
        
        //Image now displayed in BLUE color as this is DEFAULT tint
        let imageView2 = UIImageView()
        imageView2.frame = CGRect(x: 300, y: 50, width: 200, height: 200)
        imageView2.contentMode = .scaleAspectFit
        view.addSubview(imageView2)
        
        let myImageName2 = "apple_logo.png"
        let myImage2 = UIImage(named: myImageName2)
        imageView2.image = myImage2?.withRenderingMode(.alwaysTemplate)
        
        //Image now displayed in RED color
        let imageView3 = UIImageView()
        imageView3.frame = CGRect(x: 550, y: 50, width: 200, height: 200)
        imageView3.contentMode = .scaleAspectFit
        view.addSubview(imageView3)
        
        imageView3.image = myImage2?.withRenderingMode(.alwaysTemplate)
        imageView3.tintColor = UIColor.red
        
        
    }
    
    
}

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.