OpenGL string printer


Well… I meant to do this a lot earlier and indeed having this would have saved me flooding the console with junk – not an ideal way to debug!

I wanted a few things from my string printer, first of all I wanted it to scale with the screen (regardless of screen ratio) I decided to have characters nominally 16×16 (but the textures are larger than this, at a nominal resolution of 640×480 this gives 40×30 characters on the screen.  Because my codebase can be easily “ported” to GLES I decided to keep my texture size to a power of 2 size (512×256)

A texture of this size allows a character cell of 32×42 pixels for each characters texture, remember on a desktop the screen resolution could be large enough to need a decent sized texture. A character cell of 42 pixels high actually only uses 252 lines of the texture but we can live with 4 wasted lines. Of course if you have a more modest target you can always have a 256×128 texture with 16×22 characters…

Although I’m using a boring white font, there is no reason at all that you can’t use a multi coloured texture or even with some easy modification an animated texture.

In the example code I’ve included below and as you can see in the above screenshot, I’m using two sizes of fonts, to use my routines first you must set up the string printer

        Print printer =  new Print("data/font.png",24,32);
        Print smlPrint = new Print("data/font.png",16,16);

16×16 is our nominal font size, so simply supply a larger size when you create the string printing object if you want a BIG FONT!.

Two things need to be done before actually printing


first set up your blending – this is separate as you may well already be using this blending mode, leading to unnecessary state changes.  Next we tell the printer we’re just about to render, this gives the printer the opportunity to set up OpenGL the way it needs to – selecting the buffers and shaders etc.  The width and height we supply is the current size of our window (not our nominal 640×480)

Now we can actually print


The x & y coordinate are using our nominal 640×480 resolution thats scaled to the current screen resolution.

finally allow the printer to tidy up


and thats all there is to it…

here’s the code Enjoy!

Leave a Reply

Your email address will not be published.