iOS SpriteKit how to create a node with an image from a folder within app bundle?

自古美人都是妖i 提交于 2019-12-08 21:23:38

问题


I'm trying to create a sprite of a random monster where my images are stored in a folder referenced within the main bundle.

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];

When I run my code above, I get this error

SKTexture: Error loading image resource: "random_monster.png"

The code works if I reference the image from the main bundle. How can I use a random image from a folder within the app bundle and pass it to SKSpriteNode?


回答1:


In that case you can't use the spriteNodeWithImageNamed: method. You have to create the texture yourself from an absolute path and initialize your sprite with that texture:

NSImage *image = [[NSImage alloc] initWithContentsOfFile:absolutePath];
SKTexture *texture = [SKTexture textureWithImage:image];
SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithTexture:texture];

Note that doing so you will lose the performance optimizations that come with using spriteNodeWithImageNamed: (such as caching and better memory handling)

I recommend putting your images in the main bundle and use a specific naming scheme like this:

monster_001.png
monster_002.png
monster_003.png
etc...

Alternatively, consider using texture atlases.




回答2:


Actually [SKSpriteNode spriteNodeWithImageNamed:] works for me using an absolute path, at least on OSX 10.9. I'm working on a project where I need to access resources outside the app bundle and it's doing the job without needing SKTexture or NSImage.

Try it :D

NSString *imagePath = @"~/Desktop/test.png";
SKSpriteNode *test = [SKSpriteNode spriteNodeWithImageNamed:[imagePath stringByExpandingTildeInPath]];


来源:https://stackoverflow.com/questions/20304507/ios-spritekit-how-to-create-a-node-with-an-image-from-a-folder-within-app-bundle

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