The correct way to draw text in OpenGL ES 2

Huy Tran picture Huy Tran · Aug 1, 2012 · Viewed 17k times · Source

I am using PowerVR OpenGL ES 2 SDK to develop my game on Windows with C++ then I can port it to android or iphone.

Everything look alright but I'm now stuck with text rendering. I can't found any detailed tutorial about rendering text (using TTF or Bitmap font) in OpenGL ES 2.0 by using C++. I found many topic talk about rendering text on android or iphone by using java or objective-c (with a textview, surfaceview or some blah blah things) but I don't think that's what I need. I need a "cross-platform solution". (or may be I am wrong at this point?)

After a little research, I have the solution in my mind:

Load and bind bitmap font texture -> Parse text and generate and bind vertices array, mapping texture with uv array,... -> Render it to screen

I'm not tested yet but I think it's a problem when using my solution: When I want to change text (for example: I am making a user score, or a timer on screen) I must re-bind the vertices array and uv array, it's not a good idea, right?

Is there any better way/right way to draw bitmap font on screen with OpenGL ES 2?

Answer

rotoglup picture rotoglup · Aug 3, 2012

The solution that you mention is the way to go, and indeed, if you modify your text, you'll have to recreate the geometry that represents it, and resubmit it to OpenGL.

This recreation step will take some time, but surely not excessively much.

For rendering text, the problem has two main components :

  • create your texture atlas bitmap
  • draw the text using this texture, considering the font metrics (size, kerning, etc.) and possibly subpixel antialiasing

To create your texture atlas, you can find some code around (probably using freetype) or use an existing tool (such as AngleCode's bmfont).

For drawing, you'll probably want to roll out your own code, based on some existing code, as there are lot of details to get right for good looking text. To start your headache, you can have a look at this article.

One good modern source of inspiration could be Nicolas Rougier's freetype-gl code.