9 Slice Sprites in cocos2d 2.x

For a project I’m doing I needed a simple 9 slice sprite, just so I could reuse as many graphics as possible. There are a few examples out there already, and I’m sure they’re great. But as things go, I just like the challenge, and it only took me an hour and a half to finish. The basics of it is, you create a sprite with a file or from a SpriteFrame, and then the size of your insets. then you can scale, rotate, resize do what you like.

The code is on bitbucket, pull it down and have a play.
git@bitbucket.org:6foot3foot/cocos2d.git

Usage is:

CCSprite9Slice *spriteOne = [CCSprite9Slice spriteWithSpriteFrameName:@"button_pause.png" inset:CGSizeMake(6,6)];
[self addChild:spriteOne];

CCSprite9Slice *spriteTwo = [CCSprite9Slice spriteWithFile:@"scaleGraphic.png" inset:CGSizeMake(10, 16)];
[self addChild:spriteTwo];

[spriteOne setSize:CGSizeMake(100, 200)];

[spriteOne setPosition:ccp(80, 160)];

[spriteTwo setPosition:ccp(300, 160)];

[spriteOne setSize:CGSizeMake(150, 120)];

9 Slice sprites are great for menus and buttons, and hopefully this class will help others.

Leave a Reply