Follow LostMuser on Twitter

Thursday, January 7, 2010

How to do Font Rendering in OpenGL on the iPhone

Want to render iPhone fonts using OpenGL? Here is the Right Way™ to do it.


Font font("Helvetica");

font.print("Hello World", 0, 0, 0);




The font is loaded directly from the iPhone's font set. You don't have to bundle a font with your App and you get international support. You can use ASCII or UTF8.


// Hello World in Chinese (UTF8 format)
const char str[] = { 0xe4, 0xb8, 0x96, 0xe7, 0x95, 0x8c, 0xe6, 0x82, 0xa8, 0xe5, 0xa5, 0xbd, 0 };

font.print(str, 0, 0, 0);


The used glyphs are saved into OpenGL textures "on demand", providing full international support without bogging down the iPhone.

To use it, unzip the file and drag the 'Font' folder to the left Xcode panel.


Below are the docs for the Font class. You can also get the same info inside 'font.h'.


Font(string family = "Helvetica", int size = 36)
Font(int size, string family = "Helvetica")

- Construct a font by name 'family' of 'size' points.

void print(string text, float x, float y, float z,
int align = -1, float scale = 1.0f)

- Prints 'text' at location 'x', 'y', 'z'.
The text can be left, center, or right
aligned by setting 'align' to -1, 0, or
1 respectively. The text can be
crudely scaled by setting 'scale' to a
multiplier.

+ Example:
Font font;
font.print("Hello World!", 0, 0, 0);


PrintStream print(float x, float y, float z,
int align = -1, float scale = 1.0f)

- Starts a PrintStream at location 'x', 'y', 'z'.
The text can be left, center, or right aligned
by setting 'align' to -1, 0, or 1 respectively.
The text can be crudely scaled by setting
'scale' to a multiplier. The PrintStream can
be written to using operator << in a similar
manner to cout. The PrintStream can be
written to multiple times
(ie. print(0, 0, 0) << "FPS: " << 30).

+ Example:
Font font;
font.print(0, 0, 0) << "Hello World!";


struct Size { int width, height; };

Size getSize(string text, float scale = 1.0f)

- Returns the dimensions of 'text' as it will be
drawn. The text size can be crudely scaled
by setting 'scale' to a multiplier. The Size
type has two attributes: 'width' and 'height'.

4 comments:

jonnt said...

Yay I've been wanting to learn how to do this.

But I'm confused... I didn't know you could use C++ on the iPhone. That would be soooo cool.

jonnt said...

Hey are you from a.cc?

jonnt said...

Oh, well considering that you've linked this article from your signature I'd say that you are...

thedingohasmybaby said...

I think that for font rendering in OpenGL, most people go straight to the Apple-supplied example Texture2D class. It's a texture upload each time a string changes, but unlike your solution the pair kerning is correct and the number of communications with the GL driver is much fewer, which makes a major difference on the iPhone.

Post a Comment

Musing's Blog Viewer Webcam