How to grab a screenshot in sprite kit?
-
20-12-2019 - |
Question
When I am trying to grab a screen shot in spritekit. I've tried all the methods I can find online. They are not working.
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *gameOverScreenImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
just not working
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, scale);
[self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
cant recognize self.bounds and scale.
Solution
I’m not sure whether -drawViewHierarchyInRect:afterScreenUpdates:
is supposed to work with SKView (I assume so), but the reason that second example doesn’t compile is that (1) you’re trying to call it and bounds
on self
(presumably a UIViewController) rather than self.view
and (2) you haven’t defined the value of scale
. Just change those two lines:
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, [UIScreen mainScreen].scale);
[self.view drawViewHierarchyInRect:self.view.bounds afterScreenUpdates:YES];
Also, the second parameter to UIGraphicsBeginImageContextWithOptions
—“opaque”—shouldn’t be NO unless your view is transparent, and setting “afterScreenUpdates” to YES is only necessary in some circumstances which probably don’t include this one. You may see better performance by changing those.