【转载】Cocos2D里制作可以保持圆角的CCSprite的方法
本文纯属转载,并为实验
在游戏里做一个比较通用的提示框,这个提示框的背景是一个CCSprite。根据 提示框内容的多少,CCSprite可以自动缩放。问题是在UIView里UIImage是可以设置圆角保持的,但是在Cocos2D里怎么实现呢?
根据 QuartzDemo官方例子,给出了解决方法。帖子地址 http://www.cocoachina.com/bbs/read.php?tid-17140.html
代码
@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