Create multi-line labels with cocos 2d iphone


Update: This code is obsolete now. You can just do

Label *messageLabel = [Label labelWithString:message dimensions:CGSizeMake(380, 120) alignment:UITextAlignmentCenter fontName:@"your_custom_font" fontSize:26];

by using the new FontManager class. For example, run this once in your app delegate when your program first loads

[[FontManager sharedManager] loadFont:@"your_custom_font"];

It can take a long NSString and create multiple labels without breaking up a word. I’ll eventually use this for my help screen, replacing the current 6 different 480×320 png images that I load for each one ;) .

The code is simple, but hopefully it might save somebody the time it took me to write it. I had to look up some very basic elements of ObjC here, so if there is a much easier way to do this, please let me know but don’t make too much fun of me.

You can easily switch out the BitmapFontAtlas for just a normal Label and it would work just fine.

 (void) setTipString:(NSString*)str {
 
	NSInteger lineChars = 0;
	BOOL isSpace = NO;
	NSInteger index = 0;
	NSInteger numLines = 0;
 
	NSMutableString *line = [NSMutableString stringWithCapacity:LINE_LENGTH];
 
	while (index <= [str length]) {
		if(index == [str length]) {
			BitmapFontAtlas *tip = [[BitmapFontAtlas bitmapFontAtlasWithString:[NSString stringWithString:line] 
																																 fntFile:@"text.fnt"
																															 alignment:UITextAlignmentLeft] 
															retain];
			[tip setPosition: cpv(30,210 - 20 * numLines)];
			[self addChild:tip];	
			return;
		}
 
 
		NSString *tmp = [str substringWithRange:NSMakeRange(index, 1)];
		[line appendString:tmp];
 
		if([tmp isEqual:@" "])
			isSpace = YES;
		else
			isSpace = NO;
 
		if(lineChars >= LINE_LENGTH && isSpace) {
			BitmapFontAtlas *tip = [[BitmapFontAtlas bitmapFontAtlasWithString:[NSString stringWithString:line] 
																																 fntFile:@"text.fnt"
																															 alignment:UITextAlignmentLeft] 
															retain];
			[tip setPosition: cpv(30,210 - 20 * numLines)];
			[self addChild:tip];	
			lineChars = -1;
			[line setString:@""];
			numLines++;
		}
		lineChars++;
		index++;
	}
}
  1. No comments yet.
(will not be published)

  1. No trackbacks yet.