iOS Swift create new UIImage with a different color

This is very useful as you might want to create the same image in various different colors based on a user selected theme for your app.

iOS Swift create new UIImage with a different color
iOS Swift create UIImage in Gradient color example

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
        
        //Let's change the image to RED color
        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!.maskWithColor(color: UIColor.red)
                
    }
    
    
}

extension UIImage {
    func maskWithColor(color: UIColor) -> UIImage? {
        
        let maskImage = self.cgImage
        let width = self.size.width
        let height = self.size.height
        let bounds = CGRect(x: 0, y: 0, width: width, height: height)
        
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
        let bitmapContext = CGContext(data: nil,
                                      width: Int(width),
                                      height: Int(height),
                                      bitsPerComponent: 8,
                                      bytesPerRow: 0,
                                      space: colorSpace,
                                      bitmapInfo: bitmapInfo.rawValue)
        
        bitmapContext!.clip(to: bounds, mask: maskImage!)
        bitmapContext!.setFillColor(color.cgColor)
        bitmapContext!.fill(bounds)
        
        if let cImage = bitmapContext!.makeImage() {
            let coloredImage = UIImage(cgImage: cImage)
            return coloredImage
        }
        else  {
            return nil
        }
    }
}


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.