Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render/Snapshot SpriteKit Scene to NSImage

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.

like image 324
poundev23 Avatar asked Dec 18 '13 17:12

poundev23


1 Answers

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.

like image 58
rickster Avatar answered Oct 19 '22 09:10

rickster