Rizwan Shaikh Rizwan Shaikh - 3 months ago 26
Swift Question

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

Answer

You can also use this extension:

extension UIImage {
    func imageWithColor(tintColor: UIColor) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)

        let context = UIGraphicsGetCurrentContext() as CGContextRef
        CGContextTranslateCTM(context, 0, self.size.height)
        CGContextScaleCTM(context, 1.0, -1.0);
        CGContextSetBlendMode(context, kCGBlendModeNormal)

        let rect = CGRectMake(0, 0, self.size.width, self.size.height) as CGRect
        CGContextClipToMask(context, rect, self.CGImage)
        tintColor.setFill()
        CGContextFillRect(context, rect)

        let newImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage
        UIGraphicsEndImageContext()

        return newImage
    }
}

And then

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