Dave G Dave G - 7 months ago 29
Swift Question

Programatic Screenshot of Container Hidden Behind an Image

So I'm already using this code to screenshot a particular area (a table cell) that's visible on the screen:

UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, false, 0.0)
inputView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext() as UIImage
UIGraphicsEndImageContext()
let cellSnapshot : UIView = UIImageView(image: image)


However, now my goal is something more complicated:


  1. First, programmatically screenshot entire screen

  2. Present that to the user, essentially blinding them for a moment

  3. Then I'll move some stuff around behind the image



Tricky part... While the image is still hiding the new setup, I want to screenshot/capture an image of that arrangement of views (includes every single view under the image).

Why Do This? The VC doesn't change but I'm going to slide in the 2nd image, giving the appearance that this new arrangement is a new screen.

Is this possible?

Answer

So here's the code to take a snapshot of any view! Just paste this function in and pass it the view you want to capture!

let pictureOfView = snapshotOfView(passAViewHere)

func snapshotOfView (inputView: UIView) -> UIView {
    UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, false, 0.0)
    inputView.layer.renderInContext(UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext() as UIImage
    UIGraphicsEndImageContext()
    let cellSnapshot : UIView = UIImageView(image: image)
    cellSnapshot.layer.masksToBounds = false

    return cellSnapshot
}