Getting and using GraphicFont

First, download the Java source and/or class. It's quite tiny:

GraphicFont.java
GraphicFont.class

GraphicFont was designed to have a similar interface to the Font and FontMetrics classes supplied by Sun, so changing programs to support GraphicFont is a fairly easy thing to do.

In your program, make sure you import the class:

import GraphicFont;

To begin using the class, you must first load an image encoded in the GraphicFont format. The image must be fully loaded before you pass it to GraphicFont, or Bad Things might happen. You should use the MediaTracker to ensure things are loaded.

You then want to instantiate a new GraphicFont with the image.

Image fontImage;
MediaTracker tracker;
GraphicFont gf;
...
tracker = new MediaTracker(this);
...
try {
	fontImage = getImage(FONT_URL);
	tracker.addImage(fontImage, 0);
	tracker.waitForID(0);
	gf = new GraphicFont(fontImage);
} catch (Exception e) {
	;
}
Now you can do all sorts of things with your font. For instance, you can use drawString() very much like you use the regular drawString():

g = getGraphics();
gf.drawString(g, "This is a line of text.", 10, 10);
You can also set the foreground and background color of the font. The default background is transparent, and the default foreground is black. If the font is antialiased, setting a background will ensure that the characters blend smoothly into the background:

gf.setColor(new Color(20, 50, 20));
gf.setBgColor(Color.red);

// resets the background to transparent
gf.setBgColor(null);
Character width and string width functions are also available:

String s = "Some string...";
int width = gf.stringWidth(s);
gf.drawString(g, s, (appletWidth - width) / 2, 50);

int aWidth = gf.charWidth('a');
Functions that return images are also available. Note that the image may not be completely done when returned from the function. You can render entire left-justified text blocks using stringImage():

Image graphicText = gf.stringImage("Some string");

int width = 50;
Image graphicTextBlock = gf.stringImage("Some string " +
"that will be wrapped around when it gets longer than " +
"50 pixels.", width);
You can get and set values such as leading, ascent, and descent:

int ascent = gf.getAscent();
gf.setLeading(20);
That's the end of the quick tour. To get a rundown of all the functions available, please refer to the GraphicFont API.

You can use GraphicFont for commercial as well as noncommercial purposes - please refer to the header in the source code for more information regarding the license.