Thursday, November 12, 2009

Enhanced Fonts in cocos2d

One thing I came across in cocos2d was an issue with the font rendering. Since the fonts produced by Hiero bitmap font editor are very tightly packed on their containing images, rendering artefacts can appear when cocos2d displays the characters on screen.

Several people have reported these issues but I did not find a solution that fixes the problem in all cases. For that reason I have slightly amended the Hiero bitmap font editor: the modified editor outputs the fonts with more space between individual characters and amending the characters rectangles in the font definition files. This works very well and fixes the issue for me. I'll try to get in touch with Hiero's maintainer (who seems to be this guy) and will check whether there is any chance of having this feature integrated into the official version of the editor.

Another thing relating to fonts is the calculation of a string's width and, based on these calculations, a proper algorithm for line and page breaking. As I did not find such a facility within cocos2d source code, I enhanced the BitmapFontAtlas class to provide all of these. Basically, before calling [label setString:@""] to set the text for a label, you can assign a size to the label using

label.size = CGSizeMake(width, height);

If such a size has been assigned, a call to

[label setString:@"A very long string with reeeeeaaaaalllllllyyyyyyyyyyyyyyyyyyy long words and\nforced line breaks."];

will split the string according to the given size. The string will first be divided into lines (obeying the maximum width assigned earlier), then into pages (additionally obeying the maximum height). The first page will then be used as the string displayed by the label.

To choose a different page and figure out the amount of pages available within the label, you can then use the properties label.currentPage and label.pages respectively. If you assume that you want to switch to page 1 and this is within the amount of pages available, you can just assign label.page = 1 and be done.

If you don't assign a size before your call to [label setString:@""], the text is going to be rendered as with the unmodified version of BitmapFontAtlas. The only added benefit is that forced line-breaks using @"\n" are supported.

For this change, too, I'll try to contribute back to the cocos2d project. I will keep you updated!

No comments:

Post a Comment