@cocos
Sure. The header is in the previous post, here is the .mm file:
#import "TextureLoader.h"
#define PRINT_INFO 0
@implementation TextureLoader
+(CCSprite*) add:(NSString*) spriteName to:(CCNode*) cNode
{
return [self addSpriteWithName:spriteName toNode:cNode withZ:0];
}
+(CCSprite*) add:(NSString*) spriteName to:(CCNode*) cNode withZ:(int) zVal
{
return [self addSpriteWithName:spriteName toNode:cNode withZ:zVal];
}
+(CCSprite*) addSpriteWithName:(NSString *) spriteName toNode:(CCNode*) cNode
{
return [self addSpriteWithName:spriteName toNode:cNode withZ:0];
}
+(CCSprite*) addSpriteWithName:(NSString *) spriteName toNode:(CCNode*) cNode withZ:(int) zVal;
{
#if PRINT_INFO
NSLog(@"ADDING SPRITE - %@", spriteName);
#endif
CCSprite * sprite = [self getSprite:spriteName];
if(sprite)
[cNode addChild:sprite z:zVal];
return sprite;
}
+(CCSprite*) getSprite:(NSString*) spriteName
{
#if PRINT_INFO
NSLog(@"GETTING SPRITE - %@", spriteName);
#endif
CCSpriteFrame * spriteFrame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:spriteName];
if(spriteFrame)
return [CCSprite spriteWithSpriteFrame:spriteFrame];
else
return [CCSprite spriteWithFile:spriteName];
}
+(CGRect) getTextureRectForSpriteNamed:(NSString*) spriteName
{
CCSpriteFrame * tempSpriteFrame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:spriteName];
if(tempSpriteFrame)
{
return tempSpriteFrame.rect;
}
else
return CGRectZero;
}
+(CCSpriteFrame*) getSpriteFrame:(NSString*) spriteName
{
#if PRINT_INFO
NSLog(@"GETTING SPRITEFRAME - %@", spriteName);
#endif
CCSpriteFrame * fr = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:spriteName];
if(fr)
return fr;
else
{
NSLog(@"FALLBACK METHOD - POSSIBLY UNSAFE");
CCSprite * temp = [CCSprite spriteWithFile:spriteName];
if(temp)
{
CCSpriteFrame * frame = [CCSpriteFrame frameWithTexture:temp.texture rect:temp.textureRect];
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFrame:frame name:spriteName];
return frame;
}
return nil;
}
return nil;
}
#undef PRINT_INFO
@end
Usage is pretty simple:
1) set PRINT_INFO to 1 to see debug output (often helps tracing which sprite/spriteframe is missing from the project)
2) for creating sprites and adding to a node - CCSprite * spr = [TL add:@"sprite.png" to:someNode withZ:1]; - this will try to add a sprite from sprite frame cache (which is "better") and if not then will try to load sprite from file
3) getTextureRectForSpriteNamed and getSpriteFrame are pretty self explanatory. (The latter will add Sprite to sprite frame cache if needed)
Since those are just convenience functions - there is no TextureLoader object, so no need to alloc or dealloc anything at all
Hope it helps
EDIT: Of course I grant permission to use all the code by anyone and for anything ;)