Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to capture a view with its subviews. I'm using 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 whole screen including a button that's in front of the view. I tried these codes but it only captures 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 the snapshotViewAfterScreenUpdates(true) from here but I don't know how to implement it. I have a collectionView below the view and a button on top of the view (both are not in the view). The first codes capture everything with the button, collectionView, and subviews. The second codes capture the view without the subviews. What am I missing?

like image 347
Vinz Avatar asked Oct 22 '16 03:10

Vinz


1 Answers

This is working for me,

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)
}

Ref

like image 129
Mohammad Zaid Pathan Avatar answered Nov 15 '22 18:11

Mohammad Zaid Pathan