Predicting text pixel widths

Posts: 196
Joined: 2009.02
Post: #1
I'm using OSC's opengl text rendering code to render text to a view as a texture, and it works great but there's one thing I'm having trouble trying to do. Assuming that I never stretch the texture and used a particular font + font size, I need to be able to predict the pixel width of a given string, and I'm assuming the only info I have to go on is the string length, so I tried a combo of things including stuff like:

pixel_w = (strlen(str)*lenOffset) + (NumCaps*capsOffset) + (NumSpaces*spaceOffset);

And I can't come up with anything that always works. Has anyone encountered this issue before, and am I totally off base with my thinking?
Quote this message in a reply
Posts: 1,563
Joined: 2003.10
Post: #2
If you're using a proportional font, the only way to measure this reliably is to count up each glyph's advancement individually for every character in your string, using the same rendering and wrapping rules as used in the display code (if applicable). If OSC's OpenGL text rendering code uses UITextField on the inside, look at -[NSString sizeWithFont:] and friends. If this is on the desktop and it uses NSTextField, see -[NSAttributedString size] or -[NSString sizeWithAttributes:]. If it doesn't use Cocoa text rendering, whatever text rendering system is used on the back end should have equivalent measurement functions.
Quote this message in a reply
Post Reply