Game Development Reference
In-Depth Information
paint.setTextAlign(Paint.Align.
CENTER
);
canvas.drawText("This is a test!", canvas.getWidth() / 2, 100,
paint);
String text = "This is another test o_O";
paint.setColor(Color.
WHITE
);
paint.setTextSize(18);
paint.setTextAlign(Paint.Align.
LEFT
);
paint.getTextBounds(text, 0, text.length(), bounds);
canvas.drawText(text, canvas.getWidth() - bounds.width(), 140,
paint);
invalidate();
}
}
@Override
public void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
requestWindowFeature(Window.
FEATURE_NO_TITLE
);
getWindow().setFlags(WindowManager.LayoutParams.
FLAG_FULLSCREEN
,
WindowManager.LayoutParams.
FLAG_FULLSCREEN
);
setContentView(
new
RenderView(
this
));
}
}
We won't discuss the
onCreate()
method of the activity, since we've seen it before.
Our
RenderView
implementation has three members: a
Paint
, a
Typeface
, and a
Rect
, where we'll
store the bounds of a text string later on.
In the constructor, we create a new
Paint
instance and load a font from the file
font.ttf
in the
assets/
directory.
In the
onDraw()
method, we clear the screen with black, set the
Paint
to the color yellow, set the
font and its size, and specify the text alignment to be used when interpreting the coordinates
in the call to
Canvas.drawText()
. The actual drawing call renders the string
This is a test!
,
centered horizontally at coordinate 100 on the y axis.
For the second text-rendering call, we do something else: we want the text to be right-aligned
with the right edge of the screen. We could do this by using
Paint.Align.RIGHT
and an
x coordinate of
Canvas.getWidth()
- 1. Instead, we do it the hard way by using the bounds of the
string to practice very basic text layout a little. We also change the color and the size of the font
for rendering. Figure
4-15
shows the output of this activity.