Export SKTexture to a UIImage with alpha channel

天大地大妈咪最大 提交于 2021-01-28 19:43:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!