Search code examples
iosswiftuiimageuigraphicscontextuigraphicsrenderer

Screenshot a view with label and transparent background in iOS and upload it to server


I want to screenshot a view and create an UIImage from it. I want the transparency attribute of the view to be maintained in my image. I tried this method after creating an extension of UIImage but the background is not transparent in the resultant image when uploaded to the server.

Kindly help or point me if I am doing something wrong!! This means that the resultant png was not having transparency.

class func createTransparentImageFrom(label: UILabel, imageSize: CGSize) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(imageSize, false, 2.0)
    let currentView = UIView.init(frame: CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height))
    currentView.backgroundColor = UIColor.clear
    currentView.addSubview(label)

    currentView.layer.render(in: UIGraphicsGetCurrentContext()!)
    let img = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return img!
}

Solution

  • This was due to the fact that when we render a view the image is JPEG/JPG, so we need to convert it to png in order to get layer information.

    Try this :

    extension UIImage {
     class func createTransparentPNGFrom(label: UILabel, imageSize: CGSize) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(imageSize, false, 0)
        let currentView = UIView.init(frame: CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height))
        currentView.backgroundColor = UIColor.clear
        currentView.addSubview(label)
        currentView.layer.render(in: UIGraphicsGetCurrentContext()!)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        guard let newImg = img else {
            return nil
        }
        guard let imageData = UIImagePNGRepresentation(newImg) else {
            return nil
        }
        return UIImage.init(data: imageData)
     }
    }