Create SKTexture from SKShapeNode

Is there a way to create an SKTexture from an SKShapeNode? Form nodes are known to cause memory problems, and I'm looking for a way to create static graphics from them (preferably .png).

+7
ios objective-c sprite-kit
source share
1 answer

You can use the SKView method called textureFromNode:

Here from the help:

textureFromNode:

Renders and returns a Sprite Kit texture containing the contents of a node.

 - (SKTexture *)textureFromNode:(SKNode *)node 

Options

node

A node object representing the content that you want to display texture.

Return value

Sprite Kit script containing the held image.

Discussion The presented node should not appear in the representation presented as a scene. A new texture is created with the size equal to the rectangle returned by the node s calculateAccumulatedFrame method. If the node is not a node scene, it is displayed with a clear background color ([SKColor clearColor]).

UPDATE-- After examining SKShapeNode a bit and checking there really was a memory leak problem revolving around the destination of the path and then deleting the node, I had an idea ...

Not a completely new idea, more revised. This great idea actually allowed me to use SKShapeNodes for my heart.

pooling

Yes ... I just created the SKShapeNodes pool, which I reused as needed. What is the difference that makes :) So just redefine the path when necessary, when done by returning to your pool, and it will wait until you start playing again.

You simply redefine the path when necessary, when done by returning to your pool, and it will wait for you to play with it again later.

Create an ivar or NSMutableArray property in your SKScene name SKScene and create it when you start SKScene . You can either populate the array with your form nodes during init, or create them as needed.

This is the quick method I created to grab a new node from the pool:

 -(SKShapeNode *)getShapeNode { if (pool.count > 0) { SKShapeNode *shape = pool[0]; [pool removeObjectAtIndex:0]; return shape; } // if there is not any nodes left in the pool, create a new one to return SKShapeNode *shape = [SKShapeNode node]; return shape; } 

So, wherever you are in the scene, you need an SKShapeNode that you would do:

 SKShapeNode *shape = [self getShapeNode]; // do whatever you need to do with the instance 

When you finish using the node form, just return it to the pool and set the path. For example:

 [pool addObject:shape]; [shape removeFromParent]; shape.path = NULL; 

I know this is a workaround, not an ideal solution, but certainly it is a very viable workaround for those who want to use a large number of SKShapeNodes and not flush the memory.

+11
source share

All Articles