Skip to content
cgreening edited this page Apr 16, 2011 · 4 revisions

This is a simple font class for that reads in the bmfont format generated by the bitmap font generator at AngleCode - http://www.angelcode.com/products/bmfont/

The font code is all C++ so should work on all platforms (it does use STL, but that should be available everywhere)


To create a Font object you just need Font.h and Font.cpp

For iPhone projects you would do something like:

  NSString *path = [[NSBundle mainBundle] pathForResource:@"font" ofType:@"fnt"];
  font = new Font([path UTF8String]);

Note - this does not load up the corresponding texture for the font. This is something that you should do as part of your own setup.

To create the vertices, texcoords and indices for a string do:

  float *verticeAndTextureCoords;
  uint16_t *indices;
  int numberIndices;

  numberIndices = font->createVerticesAndTexCoordsForString("CMG Research Ltd", &verticeAndTextureCoords, &indices, 50);

Where 50 is the height in pixels of the string you want to generate.

You are responsible for freeing the data created by the createVerticesAndTexCoordsForString

   free(verticeAndTextureCoords);
   free(indices);

To draw the string

// GLES2.0 - you will need a shader program that does textures
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureId);  // bind our texture to texture0
glUniform1i(uniformTexture, 0);           // tell the program to use texture 0
glVertexAttribPointer(ATTRIB_POSITION, 2, GL_FLOAT, false, sizeof(float)*4, verticeAndTextureCoords);
glEnableVertexAttribArray(ATTRIB_POSITION);
glVertexAttribPointer(ATTRIB_TEXCOORD, 2, GL_FLOAT, false, sizeof(float)*4, verticeAndTextureCoords+2);
glEnableVertexAttribArray(ATTRIB_TEXCOORD);
glDrawElements(GL_TRIANGLES, numberIndices, GL_UNSIGNED_SHORT, indices);
// GLES1.1
glVertexPointer(2, GL_FLOAT, sizeof(GL_FLOAT)*4, verticeAndTextureCoords);
glTexCoordPointer(2, GL_FLOAT, sizeof(GL_FLOAT)*4, verticeAndTextureCoords+2);
glDrawElements(GL_TRIANGLES, numberIndices, GL_UNSIGNED_SHORT, indices);

The demo project has both of these rendering types in it.

To measure the size of a string with a specific height just do:

font->getWidthOfString("CMG Research Ltd", 50);
Clone this wiki locally