Does anyone know how to "snapshot" a complete SKView or SKScene into an NSImage?
We have been able to use the textureFromNode API to create an SKTexture from a node and all its children. But so far we can't figure out a way to extract the image data into say an NSImage. We are building a mixed Cocoa / SpriteKit app where we need to extract small thumbnails of scenes.
Again, this seems possible on iOS (to get a UIImage) using drawViewHierarchyInRect:
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, scale);
[self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
But how to do this on Cocoa with NSImage? Help.
As of OS X 10.11 (and iOS 9 and tvOS, but we'll ignore those since you're asking about NSImage), SKTexture can export its contents to a CGImageRef. So the textureFromNode approach you mention is now the first step in a working solution:
SKTexture *texture = [view textureFromNode: view.scene];
NSImage *image = [[NSImage alloc] initWithCGImage: texture.CGImage
size: view.bounds];
Note the size parameter to initWithCGImage: you can pass CGSizeZero there to make the NSImage inherit the pixel size of the CGImage, but since you might be dealing with a Retina Display you probably want the point size, which you can get from the view dimensions.
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