因为策划需要修改文字面板上的行间距,看了一阵CCLabelTTF想不出怎么改,于是上网各种找,终于在stackoverflow上找到了前辈们的解决办法。特摘录如下:
问:
Is there anyway in ios app to adjust the linespacing between the multiple lines in CCLabelTTF in cocos2d?
答:
"homemade" solution
#import <Foundation/Foundation.h> #import "cocos2d.h" @interface CCLabelTTFLineSpaced : CCLayer { } + (id) labelWithString:(NSString*)string dimensions:(CGSize)dimensions hAlignment: (CCTextAlignment)alignment fontName:(NSString*)name fontSize:(CGFloat)size lineSpace:(CGFloat)space; - (id) initWithString:(NSString*)str dimensions:(CGSize)dimensions hAlignment:(CCTextAlignment)alignment fontName:(NSString*)name fontSize:(CGFloat)size lineSpace:(CGFloat)space; @end
@implementation CCLabelTTF(Extension) + (id)labelWithString:(NSString *)string dimensions:(CGSize)dimensions hAlignment:(CCTextAlignment)alignment fontName:(NSString *)name fontSize:(CGFloat)size lineSpace:(CGFloat)space{ return [[[self alloc] initWithString:string dimensions:dimensions hAlignment:alignment fontName:name fontSize:size lineSpace:space] autorelease]; } - (id)initWithString:(NSString *)string dimensions:(CGSize)dimensions hAlignment:(CCTextAlignment)alignment fontName:(NSString *)name fontSize:(CGFloat)size lineSpace:(CGFloat)space { if (self = [super init]) { anchorPoint_ = ccp(0.5f, 0.5f); [self setContentSize:dimensions]; int pos = 0; int ii = 0; while (pos < [string length]) { int end = 0; int lastCut = -1; bool finished = NO; while (finished == NO) { CGSize actualSize = [[string substringWithRange:NSMakeRange(pos, end)] sizeWithFont:[UIFont fontWithName:name size:size]]; if (actualSize.width > dimensions.width || pos+end == [string length]) { if (pos+end == [string length] && actualSize.width <= dimensions.width) { lastCut = end; } finished = YES; }else { if ([[string substringWithRange:NSMakeRange(pos+end, 1)] isEqualToString:@" "] || [[string substringWithRange:NSMakeRange(pos+end, 1)] isEqualToString:@"."] || [[string substringWithRange:NSMakeRange(pos+end, 1)] isEqualToString:@""]) { lastCut = end; } end++; } } NSString *strLine = [string substringWithRange:NSMakeRange(pos, lastCut)]; CCLabelTTF *line = [CCLabelTTF labelWithString:strLine dimensions:CGSizeMake(dimensions.width, size*2) hAlignment:alignment fontName:name fontSize:size]; [line setAnchorPoint:ccp(0, 0)]; [line setPosition:ccp(0, -ii*(space+size))]; [self addChild:line]; pos = pos + lastCut; ii++; } } return self; } @end
原地址:http://stackoverflow.com/questions/7856833/line-spacing-in-cclabelttf