How to save a screenshot of a view with its subspecies in Swift?

I want to capture a performance with its subviews. I use this code to capture the screen:

let view = self.faceTrackerContainerView

UIGraphicsBeginImageContext(CGSizeMake(view.bounds.size.width, view.bounds.size.height))
UIGraphicsGetCurrentContext()!
self.view?.drawViewHierarchyInRect(view.frame, afterScreenUpdates: true)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

UIImageWriteToSavedPhotosAlbum(screenshot, nil, nil, nil)

These codes capture the entire screen, including the button that is in front of the view. I tried these codes, but it captures only the main view, excluding its subviews:

let view = self.faceTrackerContainerView
let scale = UIScreen.mainScreen().scale
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, scale);

view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

UIImageWriteToSavedPhotosAlbum(screenshot, nil, nil, nil)

I also tried from here snapshotViewAfterScreenUpdates(true)but I don't know how to implement this. I have a collectionView below the view and a button on top of the view (both not in the view). The first codes capture everything with a button, collectionView, and subviews. The second codes capture the view without subviews. What am I missing?

+7
4

,

func screenShotMethod() {
    //Create the UIImage
    UIGraphicsBeginImageContext(faceTrackerContainerView.frame.size)
    faceTrackerContainerView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    //Save it to the camera roll
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}

+8

It is not very elegant, but it hides the view before taking a picture. Then you can make them visible.

view.isHidden = true

//screenshot

view.isHidden = false
+1
source
extension UIView {
    func asImage() -> UIImage {
        let renderer = UIGraphicsImageRenderer(bounds: bounds)
        return renderer.image { rendererContext in
            layer.render(in: rendererContext.cgContext)
        }
    }
}

This makes UIImage from a UIView. Then you can use this image using UIImageView (image method :)

+1
source

Source: https://habr.com/ru/post/1658517/


All Articles