I’ve spent the latest 10 days working on a iOS/Cocos2D popups engine for my games. As Paul Legato wrote on his blog, ❝custom dialog boxes are a must for any game❞, displaying system popups in a game can interrupt the gameplay experience.
I wanted a popup that can adapt its size to every kind of content. That’s where you need a Scale9Grid component. Scale9Grid was popularized by Flash and ActionScript 3. It’s a way to scale an image while preserving the corners proportions. Only the borders and the center of the sprite are scaled. Scale9Grid explanations and illustration on this page.
Scale9Grid is also provided by Apple in UIKit UIImage method - (UIImage *) stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight.
Example of Scale9Grid with UIImage:
UIImageView *theImageView=[[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"backpanel.png"] stretchableImageWithLeftCapWidth:32 topCapHeight:32]]; theImageView.frame = CGRectMake(0,0,400,300);
UPDATE [01/12/2012] Also provided natively by Android with 9-Patch (Nine-Patch), a simple guide to 9-Patch.
I was surprised not to find a Scale9Grid implementation for Cocos2D, as the community is quite active. This is fixed now, here is a CCSpriteScale9 class for Cocos2D that implements Scale9Grid.
How you use it?
CCSpriteScale9 *bg=[CCSpriteScale9 spriteWithFile:@"backpanel.png" andLeftCapWidth:32 andTopCapHeight:32]; [bg setColor:ccc3(255,0,0)]; [bg adaptiveScale9:CGSizeMake(400,300)]; [self addChild:bg];
Scale9Grid can be used for many more than popups backgrounds.
You can see here screenshots of CCSpriteScale9 in action in my games. It’s used for popups, buttons, progress bars, input fields…
Next, I’ll post a CCPorgressBar class using the CCSpriteScale9 component. Stay tuned and follow me on twitter (@jpsarda) to be notified first.
Improvement idea. CCSpriteScale9 only preserves the corners proportions. That means the center of the sprite is usually made of a uniform color (or gradient). An alternative to scaling, would be to repeat the inside texture. That would constraint the size of the sprite to a multiple of the inside size, but that would allow every kind of pattern.
Here is the code.It’s based on CCSprite code. It implements the CCRGBAProtocol and the CCTextureProtocol. But it can’t be added to a CCSpriteBatchNode.
UPDATED [12/07/2012], Cocos2d v2 version on GitHub » CCSpriteScale9 by Sean Christmann.
UPDATED [01/13/2012], NOW ON GITHUB » CCSpriteScale9.m and CCSpriteScale9.h.
UPDATED [06/28/2012], Ported on cocos2d v2 by Varedis on the cocos2d forums » CCSpriteScale9 V2.zip.