Skip to content

Instantly share code, notes, and snippets.

@rolandoam
Created April 28, 2010 14:32
Show Gist options
  • Save rolandoam/382212 to your computer and use it in GitHub Desktop.
Save rolandoam/382212 to your computer and use it in GitHub Desktop.
multiline BitmapFontAtlas for Cocos2D-iPhone
/*
* adapted from http://www.cocos2d-iphone.org/forum/topic/207
*
* Returns a CCNode with the string. It splits on new lines and returns the length of the final node.
* The length parameter is there to know the final length of the node (pass nil if you don't need it).
*
*
* call it this way:
*
* int length;
* CCNode *credits = [self multilineNodeWithText:creditsText length:&length];
*
*/
- (CCNode *)multilineNodeWithText:(NSString *)text length:(int *)length {
NSInteger lineChars = 0;
BOOL isSpace = NO, isNewLine = NO;
NSInteger index = 0;
NSInteger numLines = 0;
NSMutableString *line = [NSMutableString stringWithCapacity:LINE_LENGTH];
CCNode *container = [CCNode node];
while (index <= [text length]) {
if (index == [text length]) {
CCBitmapFontAtlas *tip = [CCBitmapFontAtlas bitmapFontAtlasWithString:[NSString stringWithString:line]
fntFile:@"roll_no_one_small.fnt"];
tip.anchorPoint = ccp(0,0);
tip.position = ccp(0,0 - 37 * numLines); // 35 (+2 padding) is roll_no_one_small height
[container addChild:tip];
// set length output parameter if needed
if (length) {
*length = 37 * numLines;
}
return container;
}
NSString *tmp = [text substringWithRange:NSMakeRange(index, 1)];
[line appendString:tmp];
if ([tmp isEqual:@" "])
isSpace = YES;
else
isSpace = NO;
if ([tmp isEqual:@"\n"])
isNewLine = YES;
else
isNewLine = NO;
if ((lineChars >= LINE_LENGTH && isSpace) || isNewLine) {
CCBitmapFontAtlas *tip = [CCBitmapFontAtlas bitmapFontAtlasWithString:[NSString stringWithString:line]
fntFile:@"roll_no_one_small.fnt"];
tip.anchorPoint = ccp(0,0);
tip.position = ccp(0,0 - 37 * numLines);
[container addChild:tip];
lineChars = -1;
[line setString:@""];
numLines++;
}
lineChars++;
index++;
}
// we should never reach this
return nil;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment