@interface StretchableSprite : CCSprite { } +(id)spriteWithFile:(NSString*)file size:(CGSize)size leftCap:(NSInteger)leftcap topCap:(NSInteger)topcap; -(id)initWithFile:(NSString*)file size:(CGSize)size leftCap:(NSInteger)leftcap topCap:(NSInteger)topcap; @end @implementation StretchableSprite +(id)spriteWithFile:(NSString*)file size:(CGSize)size leftCap:(NSInteger)leftcap topCap:(NSInteger)topcap{ return [[[self alloc] initWithFile:file size:size leftCap:leftcap topCap:topcap] autorelease]; } -(id)initWithFile:(NSString*)file size:(CGSize)size leftCap:(NSInteger)leftcap topCap:(NSInteger)topcap{ UIImage* image = [UIImage imageNamed:file]; CGImageRef base = image.CGImage; CGContextRef context = CGBitmapContextCreate(nil, size.width, size.height, CGImageGetBitsPerComponent(base), 4 * size.width, CGImageGetColorSpace(base), kCGImageAlphaPremultipliedLast | kCGBitmapByteOrderDefault); float BASE_COL_WIDTH[] = {leftcap,1,image.size.width - leftcap -1}; float BASE_ROW_HEIGHT[] = {topcap,1,image.size.height - topcap -1}; float BASE_COL_X[] = {0,leftcap,leftcap + 1}; float BASE_ROW_Y[] = {0,topcap,topcap +1}; float TARGET_COL_WIDTH[] = {BASE_COL_WIDTH[0], size.width - BASE_COL_WIDTH[0] - BASE_COL_WIDTH[2], BASE_COL_WIDTH[2]}; float TARGET_ROW_HEIGHT[] = {BASE_ROW_HEIGHT[0], size.height - BASE_ROW_HEIGHT[0] - BASE_ROW_HEIGHT[2], BASE_ROW_HEIGHT[2]}; float TARGET_COL_X[] = {0,TARGET_COL_WIDTH[0],TARGET_COL_WIDTH[0]+TARGET_COL_WIDTH[1]}; float TARGET_ROW_Y[] = {size.height - TARGET_ROW_HEIGHT[0], size.height - TARGET_ROW_HEIGHT[0] - TARGET_ROW_HEIGHT[1], size.height - TARGET_ROW_HEIGHT[0] - TARGET_ROW_HEIGHT[1] - TARGET_ROW_HEIGHT[2]}; for (int row=0; row<3; row++) { for (int col=0; col<3; col++) { CGRect source = CGRectMake(BASE_COL_X[col], BASE_ROW_Y[row], BASE_COL_WIDTH[col], BASE_ROW_HEIGHT[row]); CGRect target = CGRectMake(TARGET_COL_X[col], TARGET_ROW_Y[row], TARGET_COL_WIDTH[col], TARGET_ROW_HEIGHT[row]); CGImageRef ref = CGImageCreateWithImageInRect(base, source); CGContextDrawImage(context, target, ref); CFRelease(ref); } } CGImageRef final = CGBitmapContextCreateImage(context); CGContextRelease(context); return [super initWithCGImage:final key:@"stretchable"]; } @end