将生成的 SKTexture 保存到文件

Save generated SKTexture to file

I've now filed a bug for the issue below. Anyone with a good workaround?

我尝试将 SKTexture 保存到文件中,然后重新加载它,但我没有成功。以下代码片段可以复制到Xcode启动项目GameScene.m中。

我在 generateTexture 中使用 textureFromNode,这似乎是我问题的根本原因。如果我使用 sprite 中的纹理,代码可以运行,并且可以看到两艘宇宙飞船。

此代码在 iOS 8 中有效,但在 Xcode7 和 iOS 9 中停止工作。我只想在提交错误报告之前验证这是一个错误.我担心 NSKeyedArchiver.

做错了什么

它在模拟器和设备上都会发生。

#import "GameScene.h"

@implementation GameScene

// Generates a texture
- (SKTexture *)generateTexture
{
    SKScene *scene = [[SKScene alloc] initWithSize:CGSizeMake(100, 100)];

    SKShapeNode *shapeNode = [SKShapeNode shapeNodeWithRectOfSize:CGSizeMake(50, 50)];
    shapeNode.position = CGPointMake(50, 50);
    shapeNode.strokeColor = SKColor.redColor;
    shapeNode.lineWidth = 10;
    [scene addChild:shapeNode];

    SKTexture *texture = [self.view textureFromNode:scene];
    //SKTexture *texture = [SKSpriteNode spriteNodeWithImageNamed:@"Spaceship"].texture; // This works!

    return texture;
}

// Just generate a path
- (NSString *)fullDocumentsPath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *yourFileName = [documentsDirectory stringByAppendingPathComponent:@"fileName"];

    return yourFileName;
}

- (void)didMoveToView:(SKView *)view
{    
    self.scaleMode = SKSceneScaleModeResizeFill;

    // Verify that the generateTexture method indeed produces a valid texture.
    SKSpriteNode *s1 = [SKSpriteNode spriteNodeWithTexture:[self generateTexture]];
    s1.position = CGPointMake(100, 100);
    [self addChild:s1];

    // Start with saving the texture.
    NSString *fullName = [self fullDocumentsPath];
    NSError *error;
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    if ([fileMgr fileExistsAtPath:fullName])
    {
        [fileMgr removeItemAtPath:fullName error:&error];
        assert(error == nil);
    }
    NSDictionary *dict1 = [NSDictionary dictionaryWithObject:[self generateTexture] forKey:@"object"];
    bool ok = [NSKeyedArchiver archiveRootObject:dict1 toFile:fullName];
    assert(ok);

    // Read back the texture and place it in a sprite. This sprite is not shown. Why?
    NSData *data = [NSData dataWithContentsOfFile:fullName];
    NSDictionary *dict2 = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    SKTexture *loadedTexture = [dict2 objectForKey:@"object"];
    SKSpriteNode *s2= [SKSpriteNode spriteNodeWithTexture:loadedTexture];
    NSLog(@"t(%f, %f)", loadedTexture.size.width, loadedTexture.size.height); // Size of sprite & texture is zero. Why?
    s2.position = CGPointMake(200, 100);
    [self addChild:s2];
}

@end

Update for Yudong:

这可能是一个更相关的例子,但假设场景由 4 个层组成,有很多精灵。比赛结束后,我想存储比赛结束场景的缩略图。该图像将用作按钮上的纹理。按下该按钮将开始重播比赛的电影。会有很多带有旧游戏图像的按钮,所以我需要将每个图像存储在文件中。

-(SKTexture*)generateTexture
{
  SKScene *scene = [[SKScene alloc] initWithSize:CGSizeMake(100, 100)];

  SKSpriteNode *ship = [SKSpriteNode spriteNodeWithImageNamed:@"Spaceship"];
  ship.position = CGPointMake(50, 50);
  [scene addChild:ship];

  SKTexture *texture = [self.view textureFromNode:scene];

  NSLog(@"texture: %@", texture);

  return texture;
}

The solution/work around:

受 Russells 代码的启发,我做了以下工作。有效!

CGImageRef  cgImg = texture.CGImage;
SKTexture *newText = [SKTexture textureWithCGImage:cgImg];

我在 Xcode 7 中测试了您的代码,发现 generateTexture 中返回的 texture 为空。这就是为什么您无法从文件中加载任何内容,甚至没有保存任何内容的原因。

尝试使用 NSLog 记录您的纹理或精灵的描述。例如。在 generateTexture 中添加此行:

NSLog(@"texture: %@", texture);

您将在控制台中获得的内容:

texture: '(null)' (300 x 300)

您代码中的 s1dict1 也一样:

s1: name:'(null)' texture:[ '(null)' (300 x 300)] position:{100, 100} scale:{1.00, 1.00} size:{100, 100} anchor:{0.5, 0.5} rotation:0.00

dict1: { object = " '(null)' (300 x 300)"; }

您可以在 iOS 8 和 iOS 9 上进行这些测试,您可能会得到不同的结果。

我不确定为什么要将 SKShapeNode 添加到 scene,然后保存 scene 的纹理。一种解决方法是为您的 SKShapeNode 设置纹理,您的代码应该可以正常工作。

shapeNode.fillTexture = [SKTexture textureWithImageNamed:@"Spaceship"];
SKTexture *texture = shapeNode.fillTexture;
return texture;

更新:

textureFromNode在iOS中没有按预期工作,这很烦人 9.我试图通过反复试验来解决它,但最后没有运气。因此,我问你是否考虑对整个屏幕进行快照并将其设置为缩略图。这是我今天取得的进步,希望你能从中得到启发。

我在 didMoveToView 中创建了一个包含 SKLabelNodeSKSpriteNode 的场景。单击屏幕上的任意位置后,将调用 snapshot 并将缩小的屏幕截图保存在文档文件夹中。我使用代码 here.

- (UIImage *)snapshot
{
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0.5);
    [self.view drawViewHierarchyInRect:self.view.bounds afterScreenUpdates:YES];
    UIImage *snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return snapshotImage;
}

由于缩略图被保存为 UIImage,因此为 sprite 的纹理加载它应该很容易。 A sample project 演示了整个过程,它适用于 iOS 8 和 9。

我用 SKTextures 做了很多 experimenting/hacking。我的游戏使用 SKTextures。它写在Swift中。具体来说,我在 textureFromNode 和 textureFromNode:crop: 以及从纹理创建 SKPhysicsBodies 方面遇到了很多问题。这些方法在 ios 8 中运行良好,但 Apple 在发布 ios 9.0 时完全破坏了它们。在 ios 9.0 中,纹理恢复为零。那些零纹理从纹理中破坏了 SKPhysicsBodies。

我最近在研究 serialization/deserialization 的 SKTextures。

您可能会调查的一些关键 ideas/clues 是:

  1. 运行 ios 9.2。 Apple Staff 提到很多问题已得到修复。 https://forums.developer.apple.com/thread/17463 我发现 ios 9.2 对 SKTextures 有帮助,但并没有解决所有问题,尤其是序列化问题。

  2. 尝试 PrefersOpenGL(在您的配置中将其设置为 "YES" 作为布尔自定义 属性)。这是 Apple 员工在 Apple Dev Forums 中关于 PrefersOpenGL 的 post。 https://forums.developer.apple.com/thread/19683 我观察到 ios 9.x 似乎默认使用 Metal 而不是 OpenGL。我发现 PrefersOpenGL 有助于解决 SKTexture 问题,但仍然无法使我的 SKShaders 工作(用 GLSL 编写)。

  3. 当我在 ios 9.2 上尝试使用 SKTextures serialize/deserialize 节点时,我得到的是白色框而不是可见纹理。受 Apple SKTexture 文档的启发,“纹理数据在以下时间加载:

纹理对象的大小方法被调用。

调用了另一个需要纹理大小的方法,例如创建一个使用纹理对象的新 SKSpriteNode 对象。

调用了一种预加载方法(请参阅预加载纹理数据。)

纹理数据准备渲染时:

使用纹理的精灵或粒子是正在渲染的节点树的一部分。"

...我破解了一个从 CGImage() 调用创建辅助纹理的变通方法:

        // ios 9.2 workaround for white boxes on serialization
        let img = texture!.CGImage()
        let uimg = UIImage(CGImage: img)
        let ntex = SKTexture(image: uimg)
        let sprite = SKSpriteNode(texture: ntex, size: texture!.size())

所以现在我用这种方式创建的 SKSpriteNode 似乎 serialize/deserialize 没问题。顺便说一句,仅调用 size() 或使用原始纹理创建 SKSpriteNode 似乎不足以将纹理具体化到内存中。

  1. 您没有询问 textureFromNode:crop: 但我还是添加了观察结果以防万一它对您有帮助:我发现 ios 8 中的这种方法有效(尽管裁剪参数非常棘手,似乎需要使用 UIScreen.mainScreen().scale) 进行规范化。在 ios 9.0 中,此方法根本不起作用(返回 nil)。在 ios 9.2 中,此方法现在可用(它现在 returns 一个非零纹理)但是随后从纹理创建节点不需要大小标准化。此外,要使 serialization/deserialization 正常工作,我发现您最终必须执行上面的 #3。

希望对您有所帮助。我想我对 SKTextures 的挣扎比大多数人都多,因为我的应用程序非常依赖它们。