Is there anyway in ios app to adjust the linespacing between the multiple lines in CCLabelTTF in cocos2d? Thanks
The answer to you question is no. You can't adjust a CCLabelTTF linespacing. But hey! I will share with you my solution for this ;)
This is the .h
#import <Foundation/Foundation.h>
#import "cocos2d.h"
@interface CCLabelTTFLineSpaced : CCLayer {
}
+ (id) labelWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment fontName:(NSString*)name fontSize:(CGFloat)size lineSpace:(CGFloat)space;
- (id) initWithString:(NSString*)str dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment fontName:(NSString*)name fontSize:(CGFloat)size lineSpace:(CGFloat)space;
@end
And this is the .m
#import "CCLabelTTFLineSpaced.h"
@implementation CCLabelTTFLineSpaced
+ (id) labelWithString:(NSString*)string dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment fontName:(NSString*)name fontSize:(CGFloat)size lineSpace:(CGFloat)space{
return [[[self alloc] initWithString: string dimensions:dimensions alignment:alignment fontName:name fontSize:size lineSpace:(CGFloat)space]autorelease];
}
- (id) initWithString:(NSString*)str dimensions:(CGSize)dimensions alignment:(CCTextAlignment)alignment fontName:(NSString*)name fontSize:(CGFloat)size lineSpace:(CGFloat)space{
if( (self=[super init]) ) {
anchorPoint_ = ccp(0.5f, 0.5f);
[self setContentSize:dimensions];
self.isRelativeAnchorPoint = NO;
int pos = 0;
int i = 0;
while (pos<[str length]) {
int end = 0;
int lastCut = -1;
bool finished=NO;
while (finished==NO) {
CGSize actualSize = [[str substringWithRange:NSMakeRange(pos, end)] sizeWithFont:[UIFont fontWithName:name size:size]];
if (actualSize.width > dimensions.width || pos+end == [str length]) {
if (pos+end == [str length] && actualSize.width <= dimensions.width) lastCut = end;
finished=YES;
}
else {
if ([[str substringWithRange:NSMakeRange(pos+end, 1)] isEqualToString:@" "] || [[str substringWithRange:NSMakeRange(pos+end, 1)] isEqualToString:@"."] || [[str substringWithRange:NSMakeRange(pos+end, 1)] isEqualToString:@","]) {
lastCut = end;
}
end++;
}
}
NSString * strLine = [str substringWithRange:NSMakeRange(pos, lastCut)];
CCLabelTTF * line = [CCLabelTTF labelWithString:strLine dimensions:CGSizeMake(dimensions.width, size*2) alignment:alignment fontName:name fontSize:size];
[line setAnchorPoint:ccp(0,1)];
[line setPosition:ccp(0,-i*space)];
[self addChild:line];
pos=pos+lastCut;
i++;
}
}
return self;
}
@end
Easy to use ;) I have to complete the class with getters, setters and all stuff. I know that this is a "homemade" solution, but hey! It works!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With