In my iPAD application, I have two viewcontrollers, first viewcontroller has a button, I want to get the snapshot of second viewcontroler when I click on that button, without loading the second viewcontroller in iPAD screen. If I load the viewcontroler and then take snapshot then it is working but my requirement is to do the same without loading the viewcontroler in screen. Please give idea or link or code snippet.
render(in: UIGraphicsGetCurrentContext()!) let screenshot = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return screenshot! }
try this:- Make instance of VC that you want to take screen shot, and then pass the object in this method.
+ (UIImage *)renderImageFromView:(UIView *)view withRect:(CGRect)frame {
// Create a new context the size of the frame
UIGraphicsBeginImageContextWithOptions(frame.size, YES, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
// Render the view
[view.layer renderInContext:context];
//[view drawRect:frame];
// Get the image from the context
UIImage *renderedImage = UIGraphicsGetImageFromCurrentImageContext();
// Cleanup the context you created
UIGraphicsEndImageContext();
return renderedImage;
}
This solution is based on Dheeraj Kumar's answer, but this will work if your view contains SpriteKit contents as well. It requires iOS7, though.
The code in Swift, for the ViewController with the SpriteKit view,
private func takeScreenshot() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, UIScreen.mainScreen().scale)
view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
Not part of the question, but you can then share your screenshot very easily,
if let image = screenshot as? AnyObject {
let activity = UIActivityViewController(activityItems: [image], applicationActivities: nil)
self.presentViewController(activity, animated: true, completion: nil)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With