问题
I would like to be able to export my SKTexture to an external image file. I have been able to achieve this using the following code. However it suffers from the critical flaw that the alpha channel is ignored even thoough the view is not opaque and all background colours are set to clear.
- (void)export:(CGRect)bounds texture:(SKTexture *)texture path:(NSString *)path{
UIGraphicsBeginImageContextWithOptions(bounds.size, NO, [UIScreen mainScreen].scale);
SKView *view = [[SKView alloc] initWithFrame:bounds];
SKScene *scene = [SKScene sceneWithSize:CGSizeMake(bounds.size.width, bounds.size.height)];
view.opaque = NO;
view.backgroundColor = [UIColor clearColor];
scene.backgroundColor = [UIColor clearColor];
SKSpriteNode *node = [SKSpriteNode spriteNodeWithTexture:texture];
node.position = CGPointMake(bounds.size.width/2, bounds.size.height/2);
[scene addChild:node];
[view presentScene:scene];
[view drawViewHierarchyInRect:bounds afterScreenUpdates:YES];
UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[UIImagePNGRepresentation(snapshotImage) writeToFile:path atomically:YES];
}
Is there any alterations I could make the current solution to allow exporting images that include the alpha value?
Is there some more obvious approach to exporting textures to an image?
Intention: The textures I am exporting are currently generated on game load from SKShapeNode's in order to work around SKShapeNode's pitfalls. To avoid texture generation overhead I would like to export them as images and instead load these textures directly from a texture atlas.
回答1:
There doesn't appear to be anyway to achieve transparent background for exported textures.
According to this SO question SKScene cannot be transparent and the likely cause is that SpriteKit uses a framebuffer that doesn't allow for this transparency for performance reasons.
来源:https://stackoverflow.com/questions/23719627/export-sktexture-to-a-uiimage-with-alpha-channel