View Full Version : Variable width font justification
Olivier
11-14-2007, 08:07 AM
In my game which uses a variable width font I can easily display left-aligned text. The display position of the next character is calculated by adding the width of the previous character.
But what about displaying centered and right-aligned text? Is there a common practice that I'm not aware of? For example how are word processors doing it? Obviously the problem lies in not knowing the lenght of each line of text before drawing all the characters of that line.
FYI I'm not coding in C or Java or anything but I can adapt any code snippet. :D
luggage
11-14-2007, 08:26 AM
Write a function called GetStringWidth or something. Just do a fake print of your text (ie. don't actually render text but use the same process to work out what the entire visual length of the string would be).
Once you have the visual length of the string then...
centered text is: xPosition -= (stringWidth / 2.0f);
right aligned is: xPosition -= stringWidth;
Olivier
11-14-2007, 09:12 AM
Doing a fake print to get the lenght of the string before actually displaying it. Hmm.. cleverly simple must I say. Thanks a lot! :)
ggambett
11-14-2007, 10:04 AM
Scott is right. And to do text justification, the simplest way is to distribute the extra space between the N-1 spaces between the N words. That is,
nExtraSpace = nIntendedWidth - nTextWidth
nExtraWordSpacing = nExtraSpace / (nWordCount - 1)
Pogacha
11-14-2007, 06:36 PM
And take into account that if the text rendering is pixel aligned, the extra word spacing must be calculated by some sort of dithering.
Nikos Beck
11-15-2007, 08:06 AM
I draw text character-by-character using sprites. I render the first sprite, then position every subsequent sprite at an offset from the previous one. I calculate the width of the entire string and move the first sprite into position. Every other sprite moves automatically.
I handle word-wrapping in a similar way. I render all of the text in a long line, position the first character and whenever I hit the right boundary, I move the current character down by fixing the offset (and each subsequent character follows suit).
A consideration for variable-width fonts is limiting the number of characters in edit widgets. The player name is limited to eight characters (there was a discussion about how long to make character names in another thread, so please no comments about a limit of eight). I set the width of the edit widget to eight W's, WWWWWWWW, because it's the widest character and no matter what the player types in, it'll stay within the widget.
vBulletin v3.6.0, Copyright ©2000-2009, Jelsoft Enterprises Ltd.