Game Development Reference
In-Depth Information
Sometimes it's also useful to know the bounds of a specific string in pixels. For this, the
Paint
class offers the following method:
Paint.getTextBounds(String text, int start, int end, Rect bounds);
The first argument is the string for which we want to get the bounds. The second and third
arguments specify the start character and the end character within the string that should be
measured. The end argument is exclusive. The final argument,
bounds
, is a
Rect
instance we
allocate ourselves and pass into the method. The method will write the width and height of the
bounding rectangle into the
Rect.right
and
Rect.bottom
fields. For convenience, we can call
Rect.width()
and
Rect.height()
to get the same values.
Note that all of these methods work on a single line of text only. If we want to render multiple
lines, we have to do the layout ourselves.
Putting It All Together
Enough talk: let's do some more coding. Listing 4-15 shows text rendering in action.
Listing 4-15. The FontTest Activity
package
com.badlogic.androidgames;
import
android.app.Activity;
import
android.content.Context;
import
android.graphics.Canvas;
import
android.graphics.Color;
import
android.graphics.Paint;
import
android.graphics.Rect;
import
android.graphics.Typeface;
import
android.os.Bundle;
import
android.view.View;
import
android.view.Window;
import
android.view.WindowManager;
public class
FontTest
extends
Activity {
class
RenderView
extends
View {
Paint paint;
Typeface font;
Rect bounds =
new
Rect();
public
RenderView(Context context) {
super
(context);
paint =
new
Paint();
font = Typeface.createFromAsset(context.getAssets(), "font.ttf");
}
protected void
onDraw(Canvas canvas) {
canvas.drawRGB(0, 0, 0);
paint.setColor(Color.
YELLOW
);
paint.setTypeface(font);
paint.setTextSize(28);