Reputation: 81
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.
Upvotes: 6
Views: 5270
Reputation: 1963
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)
}
Upvotes: 3
Reputation: 11039
Just instantiate your second view controller, and take a screenshot, like:
- (void)foo
{
UIViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"secondVC"];
UIImage *screenShot = [self imageFromView:vc.view];
// Do something with screenShot
}
- (UIImage *)imageFromView:(UIView *) view
{
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, [[UIScreen mainScreen] scale]);
} else {
UIGraphicsBeginImageContext(view.frame.size);
}
[view.layer renderInContext: UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
Upvotes: 0
Reputation: 441
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;
}
Upvotes: 10