iOS SpriteKit 如何使用应用程序包中的文件夹中的图像创建节点?
Posted
技术标签:
【中文标题】iOS SpriteKit 如何使用应用程序包中的文件夹中的图像创建节点?【英文标题】:iOS SpriteKit how to create a node with an image from a folder within app bundle? 【发布时间】:2013-11-30 19:15:29 【问题描述】:我正在尝试创建一个随机怪物的精灵,其中我的图像存储在主包中引用的文件夹中。
NSString* bundlePath = [[NSBundle mainBundle] bundlePath];
NSString* resourceFolderPath = [NSString stringWithFormat:@"%@/monsters", bundlePath];
NSArray* resourceFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:resourceFolderPath error:nil];
NSInteger randomFileIndex = arc4random() % [resourceFiles count];
NSString* randomFile = [resourceFiles objectAtIndex:randomFileIndex];
SKSpriteNode* tile = [SKSpriteNode spriteNodeWithImageNamed:randomFile];
当我在上面运行我的代码时,我得到了这个错误
SKTexture: Error loading image resource: "random_monster.png"
如果我从主包中引用图像,则代码有效。 如何使用 app bundle 中文件夹中的随机图像并将其传递给 SKSpriteNode?strong>
【问题讨论】:
【参考方案1】:在这种情况下,您不能使用spriteNodeWithImageNamed:
方法。您必须自己从绝对路径创建纹理并使用该纹理初始化您的精灵:
NSImage *image = [[NSImage alloc] initWithContentsOfFile:absolutePath];
SKTexture *texture = [SKTexture textureWithImage:image];
SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithTexture:texture];
请注意,这样做会失去使用 spriteNodeWithImageNamed:
带来的性能优化(例如缓存和更好的内存处理)
我建议将您的图像放在主包中并使用如下特定的命名方案:
monster_001.png
monster_002.png
monster_003.png
etc...
或者,考虑使用texture atlases。
【讨论】:
是的,我刚刚发现了如何使用纹理图集来做到这一点:raywenderlich.com/45152/… spriteNodeWithImageNamed 上是否有任何来源可以准确解释它在做什么?【参考方案2】:实际上 [SKSpriteNode spriteNodeWithImageNamed:] 使用绝对路径对我有用,至少在 OSX 10.9 上是这样。我正在做一个项目,我需要访问应用程序包之外的资源,它在不需要 SKTexture 或 NSImage 的情况下完成了这项工作。
试试看:D
NSString *imagePath = @"~/Desktop/test.png";
SKSpriteNode *test = [SKSpriteNode spriteNodeWithImageNamed:[imagePath stringByExpandingTildeInPath]];
【讨论】:
以上是关于iOS SpriteKit 如何使用应用程序包中的文件夹中的图像创建节点?的主要内容,如果未能解决你的问题,请参考以下文章
每当单击刷新按钮时,如何更新 iOS 应用程序包中的嵌入式 JSON 文件