Click here to Skip to main content
15,884,836 members
Articles / Mobile Apps / iPhone

FreeType on OpenGL ES (iPhone)

Rate me:
Please Sign up or sign in to vote.
4.75/5 (10 votes)
24 Nov 2010CPOL4 min read 86.4K   3K   27  
Faster, smarter and better looking fonts rendered with OpenGL ES
#include "PreCompile.h"
#include "FTBitmapChar.h"
#include "GLCallBatcher.h"
#include "ResManager.h"
#include <freetype/ftglyph.h>


FTBitmapChar::FTBitmapChar()
{
	m_x = 0;
	m_y = 0;
	m_width = 0;
	m_height = 0;
	m_xOffset = 0;
	m_yOffset = 0;
	m_xAdvance = 0;
	m_pGlyph = NULL;
}

FTBitmapChar::~FTBitmapChar()
{
}

	

void FTBitmapChar::InitTexCoords(int texWidth, int texHeight)
{
	float x1 = (float)m_x/(float)texWidth;
	float y1 = (float)m_y/(float)texHeight;
	float x2 = (float)(m_x+m_width)/(float)texWidth;
	float y2 = (float)(m_y+m_height)/(float)texHeight;

	m_texCoords[0] = x1;
	m_texCoords[1] = y1;

	m_texCoords[2] = x2;
	m_texCoords[3] = y1;

	m_texCoords[4] = x1;
	m_texCoords[5] = y2;

	m_texCoords[6] = x2;
	m_texCoords[7] = y2;
}

// setup quad and draw as triangle groups
void FTBitmapChar::Render(int x, int y) const
{
	if (IsEmpty()) return;
	x += m_xOffset;	
	y += m_yOffset;
	float vertices[verticesPerQuad*compVertPos];
	vertices[0] = (float)x;
	vertices[1] = (float)y;

	vertices[2] = (float)(x+m_width);
	vertices[3] = (float)y;

	vertices[4] = (float)x;
	vertices[5] = (float)(y+m_height);

	vertices[6] = (float)(x+m_width);
	vertices[7] = (float)(y+m_height);
	g_resManager.GetBatcher().AddQuad(m_texCoords, vertices);
} // end of draw()


void FTBitmapChar::DrawToBitmap(unsigned char* pData, int texWidth, int texHeight) 
{
	if (IsEmpty()) return;
	InitTexCoords(texWidth, texHeight);
	// Convert The Glyph To A Bitmap.
	FT_Glyph_To_Bitmap(&m_pGlyph, FT_RENDER_MODE_NORMAL, 0, 1);
	FT_BitmapGlyph bitmap_glyph = (FT_BitmapGlyph)m_pGlyph;

	// This Reference Will Make Accessing The Bitmap Easier.
	FT_Bitmap& bitmap = bitmap_glyph->bitmap;

	assert(bitmap.width == m_width);
	assert(bitmap.rows == m_height);
	int x, y = 0;
	int index;
	for (y = 0; y < bitmap.rows; y++)
	{
		for (x = 0; x < bitmap.width; x++)
		{
			index = (m_y+y)* texWidth + m_x + x;
			pData[index] = bitmap.buffer[y*bitmap.width + x];
		}
	}
}

void FTBitmapChar::ReleaseGlyph() 
{
	if (m_pGlyph) FT_Done_Glyph(m_pGlyph);
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Astronautz
Spain Spain
After working in the software industry for many years, I've started my own games company that specialises in strategy games for mobile platforms.

Comments and Discussions