Exclude View from Screenshot

Viewed 3497

This is how I take a screenshot of my view:

UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0)
view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

However, in the view, there is a UIVisualEffectsView which I'd like to exclude from the screenshot.
I tried hiding the UIVisualEffectsView just before taking the screenshot and un-hiding it afterwards but I don't want the user to see that process. (which he does if I simply hide the view because the iPad is too slow and it looks like the screen is flickering...)

Any ideas? Thanks in advance!

4 Answers

Oh, actually, just following code (swift 4) can work. That is, create a context, and add the item you want in the snapshot. No need to add view in real screen.

Note: currentView is the view which snapshot based on, commonly, it will be view of whole screen. And addViews are the views you want to add.

func takeSnapShot(currentView: UIView , addViews: [UIView], hideViews: [UIView]) -> UIImage {


    for hideView in hideViews {
        hideView.isHidden = true
    }

    UIGraphicsBeginImageContextWithOptions(currentView.frame.size, false, 0.0)

    currentView.drawHierarchy(in: currentView.bounds, afterScreenUpdates: true)
    for addView in addViews{
        addView.drawHierarchy(in: addView.frame, afterScreenUpdates: true)
    }

    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    for hideView in hideViews {
        hideView.isHidden = false
    }

    return image!
}

Actually there is an easy way to do it.

For example we have a share button and View in storyboard and process with it in sample below code.

 @IBAction func share(_ sender: Any) {
  self.hideView.isHidden = true
  let bounds = UIScreen.main.bounds
  UIGraphicsBeginImageContextWithOptions(bounds.size, true, 0.0)
  self.view.drawHierarchy(in: bounds, afterScreenUpdates: true)
  let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
  //Add Activity view controller to use it
  self.hideView.isHidden = false
}

I used it for hiding Ads if the screenshot taken with my share button and it works for me.

afterScreenUpdates: true works here for hide to view while you click the button. It hides for millisecond hideView and took screenshot then it appears back to your view like it was never hidden.

*This is my first answer and hope it helps someone.

Thanks.

Related