How can I get screenshot of view including sublayer?

Viewed 109

I am using code below, but it doesn't include my sublayer

        //Create the UIImage
        UIGraphicsBeginImageContext(self.localVideoView!.frame.size)
        self.localVideoView!.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        //Save it to the camera roll
        UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
1 Answers

Use this extension:

extension UIView {

var screenShot: UIImage {
    return UIGraphicsImageRenderer(size: bounds.size).image { _ in
        drawHierarchy(in: bounds, afterScreenUpdates: true)
    }
  }
}

usage:

guard let image = yourView.screenShot.pngData() else { return }
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)

naturally add to your info.plist Privacy - Photo Library Additions Usage Description and Privacy and Photo Library Usage Description

Related