How to programatically take a screenshot in Sprite-Kit?

ios, screenshot, sprite-kit, uiimage

Solution

This is the best solution to take a screen shoot in your Sprite-Kit

UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 1);
[self.view drawViewHierarchyInRect:self.view.bounds afterScreenUpdates:YES];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return  viewImage;

Problem

I've been reading resolved questions on how to programmatically take a screenshot but I can't seem to get what I've read to work in sprite kit. For instance: This question How to take a screenshot programmatically ``` UIGraphicsBeginImageContext(self.window.bounds.size); [self.window.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); NSData * data = UIImagePNGRepresentation(image); [data writeToFile:@"foo.png" atomically:YES]; ``` UPDATE April 2011: for retina display, change the first line into this: ``` if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) UIGraphicsBeginImageContextWithOptions(self.window.bounds.size, NO, [UIScreen mainScreen].scale); else UIGraphicsBeginImageContext(self.window.bounds.size); ``` gave me this information, which I tested on my game but it didn't work because window was not recognized on an SKScene. I tried replacing it with scene but that didn't work. Any suggestions? I also tried this: ``` UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, scale); [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES]; UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); ``` Which I found in this question: ios Sprite Kit screengrab? But it didn't seem to work either because it didn't recognize scale, or bounds in the second line.

Original source

Related problems