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++; } }
Hey,
Why isn’t this working for me?
CCLabel *messageLabel = [CCLabel labelWithString:@"TEST" dimensions:CGSizeMake(380, 120) alignment:UITextAlignmentCenter fontName:@"pc_paint_special_gradient_green.fnt" fontSize:26];
messageLabel.position = ccp(160,240);
[self addChild:messageLabel];
What kind of error or output do you get?
@Anon: try using Label instead of CCLabel
@Eric: I am using your updated code but I am wondering if it is possible to vertically align the text within the box… is that possible?
Sorry, I just manually tweaked the spaces to get whatever alignment I was looking for. I didn’t really spend too much time to make the code easy to work across many cases.
What is LINE_LENGTH for? Where did u declare that things
It is the length of a line, in number of characters. Just replace it with a number like 60.