iosswiftuiimage

how to set a background color in UIimage in swift programming


I draw an image using drawInRect() method.

My rectangle is size of 120*120 and my image is 100 * 100.

How i can set a background color to my image in swift?


Solution

  • You can also use this extension:

        extension UIImage {
            func imageWithColor(tintColor: UIColor) -> UIImage {
                UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
    
                let context = UIGraphicsGetCurrentContext()!
                context.translateBy(x: 0, y: self.size.height)
                context.scaleBy(x: 1.0, y: -1.0);
                context.setBlendMode(.normal)
    
                let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) as CGRect
                context.clip(to: rect, mask: self.cgImage!)
                tintColor.setFill()
                context.fill(rect)
    
                let newImage = UIGraphicsGetImageFromCurrentImageContext()!
                UIGraphicsEndImageContext()
    
                return newImage
            }
        }
    
    

    And then

    image.imageWithColor("#1A6BAE".UIColor)
    

    EDIT: 2019-11: Updated to Swift 5 by @Yuto