Rizwan Shaikh Rizwan Shaikh - 1 year ago 72
Swift Question

how to set a background color in UIimage in swift programming

I draw an image using

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 Source

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)
        CGContextFillRect(context, rect)

        let newImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage

        return newImage

And then