Game Development Reference
In-Depth Information
Rendering Text
While the text we'll output in the Mr. Nom game will be drawn by hand, it doesn't hurt to know
how to draw text via TrueType fonts. Let's start by loading a custom TrueType font file from the
assets/
directory.
Loading Fonts
The Android API provides us with a class called
Typeface
that encapsulates a TrueType font. It
provides a simple static method to load such a font file from the
assets/
directory:
Typeface font = Typeface.
createFromAsset
(context.getAssets(), "font.ttf");
Interestingly enough, this method does not throw any kind of exception if the font file can't be
loaded. Instead, a
RuntimeException
is thrown. Why no explicit exception is thrown for this
method is a bit of a mystery.
Drawing Text with a Font
Once we have our font, we set it as the
Typeface
of a
Paint
instance:
paint.setTypeFace(font);
Via the
Paint
instance, we also specify the size at which we want to render the font:
paint.setTextSize(30);
The documentation of this method is again a little sparse. It doesn't tell us whether the text size
is given in points or pixels. We just assume the latter.
Finally, we can draw text with this font via the following
Canvas
method:
canvas.drawText("This is a test!", 100, 100, paint);
The first parameter is the text to draw. The next two parameters are the coordinates where the
text should be drawn to. The last argument is familiar: it's the
Paint
instance that specifies the
color, font, and size of the text to be drawn. By setting the color of the
Paint
, you also set the
color of the text to be drawn.
Text Alignment and Boundaries
Now, you might wonder how the coordinates of the preceding method relate to the rectangle
that the text string fills. Do they specify the top-left corner of the rectangle in which the text is
contained? The answer is a bit more complicated. The
Paint
instance has an attribute called the
align setting
. It can be set via this method of the
Paint
class:
Paint.setTextAlign(Paint.Align align);
The
Paint.Align
enumeration has three values:
Paint.Align.LEFT
,
Paint.Align.CENTER
, and
Paint.Align.RIGHT
. Depending on what alignment is set, the coordinates passed to the
Canvas.drawText()
method are interpreted as either the top-left corner of the rectangle, the
top-center pixel of the rectangle, or the top-right corner of the rectangle. The standard alignment
is
Paint.Align.LEFT
.