Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take snapshot of a viewcontroller without loading in screen in ios?

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.

like image 489
Sukumar Mandal Avatar asked Jul 18 '14 09:07

Sukumar Mandal


People also ask

How do you take a screenshot in Swift?

render(in: UIGraphicsGetCurrentContext()!) let screenshot = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return screenshot! }


2 Answers

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;
}
like image 56
Dheeraj Kumar Avatar answered Nov 14 '22 23:11

Dheeraj Kumar


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)
    }
like image 36
endavid Avatar answered Nov 14 '22 23:11

endavid