原文
@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 &#61; [UIImage imageNamed:file];CGImageRef base &#61; image.CGImage; CGContextRef context &#61; CGBitmapContextCreate(nil,size.width, size.height, CGImageGetBitsPerComponent(base), 4 * size.width,CGImageGetColorSpace(base), kCGImageAlphaPremultipliedLast | kCGBitmapByteOrderDefault);float BASE_COL_WIDTH[] &#61; {leftcap,1,image.size.width - leftcap -1};float BASE_ROW_HEIGHT[] &#61; {topcap,1,image.size.height - topcap -1};float BASE_COL_X[] &#61; {0,leftcap,leftcap &#43; 1};float BASE_ROW_Y[] &#61; {0,topcap,topcap &#43;1};float TARGET_COL_WIDTH[] &#61; {BASE_COL_WIDTH[0], size.width - BASE_COL_WIDTH[0] - BASE_COL_WIDTH[2], BASE_COL_WIDTH[2]};float TARGET_ROW_HEIGHT[] &#61; {BASE_ROW_HEIGHT[0], size.height - BASE_ROW_HEIGHT[0] - BASE_ROW_HEIGHT[2], BASE_ROW_HEIGHT[2]};float TARGET_COL_X[] &#61; {0,TARGET_COL_WIDTH[0],TARGET_COL_WIDTH[0]&#43;TARGET_COL_WIDTH[1]};float TARGET_ROW_Y[] &#61; {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&#61;0; row<3; row&#43;&#43;) {for (int col&#61;0; col<3; col&#43;&#43;) {CGRect source &#61; CGRectMake(BASE_COL_X[col], BASE_ROW_Y[row], BASE_COL_WIDTH[col], BASE_ROW_HEIGHT[row]);CGRect target &#61; CGRectMake(TARGET_COL_X[col], TARGET_ROW_Y[row], TARGET_COL_WIDTH[col], TARGET_ROW_HEIGHT[row]);CGImageRef ref &#61; CGImageCreateWithImageInRect(base, source);CGContextDrawImage(context, target, ref);CFRelease(ref);}} CGImageRef final &#61; CGBitmapContextCreateImage(context); CGContextRelease(context);return [super initWithCGImage:final key:&#64;"stretchable"];
}
&#64;end