Mark,
the way to draw a glyph in colour is to use the 8bpp glyph bitmap as an
alpha mask through which the foreground is drawn on to the background. For
each pixel, use the pixel's value (conceptually converting the range 0...255
to 0...1) as the proportion of the foreground colour to use. For example, if
the value is 200, the colour drawn should be a mixture of 200/255, or about
0.78, of the foreground colour and 55/255 or about 0.22 of the colour of the
background pixel already drawn at that point.
The exact way of doing this varies according to the format of the
destination bitmap (i.e., the background), but here is how to do it if the
destination bitmap is in 24bpp RGB format - that is, each pixel is
represented by 3 bytes, one each for the red, green and blue components.
For each of the three components, compute a new value using this function,
where aForeground is the value of the foreground colour component,
aBackground is the value of the background colour component, and aAlpha is
the glyph pixel value (and all three values must be in the range 0...255):
unsigned char AlphaBlend(int aForeground,int aBackground,int aAlpha)
{
int x = (aForeground - aBackground) * aAlpha;
x += (x >> 8) + 127;
return (unsigned char)(aBackground + (x >> 8));
}
This is working code from my CartoType map-drawing project, which uses
FreeType.
Note that if the destination bitmap (the background) is in a format that
includes an alpha channel, the method of blending the alpha channel values
is different; and you may have to deal with premultiplied alpha (Google for
this).
You also mentioned using a background colour, by which I assume you mean
drawing the glyphs as opaque rectangles rather than transparently. I would
not recommend this; in practically all applications it is better to draw the
glyph shapes on the current background. If you need to draw a background in
a certain colour behind some text, draw a rectangle of that colour first,
then apply the blending method I have described.
Graham Asher
Cartography Ltd.