在游戏中文本信息的输出我们可以手动绘制,现在让我们从assets/目录中加载一个自定义的TrueType字体文件。
Typeface font = Typeface.createFromAsset(context.getAssets(), "font.ttf");
如果加载失败不会抛出任何异常,而是抛出一个RuntimeException
一旦获得字体,可将其设置为Paint实例的Typeface:
paint.setTypeFace(font);
通过Paint实例设置字体大小:
paint.setTextSize(30);
最后可通过下面的Canvas方法将文本以这种字体绘制出来:
canvas.drawText("This is a test!", 100, 100, paint);
显而易见,第一个参数是要绘制的文本,接下来两个参数是绘制文本的坐标位置,最后一个是Paint实例
Paint类有个方法可以设置对齐方式:
Paint.setTextAlign(Paint.Align align);
其中Paint.Align枚举有3个值:Paint.Align.LEFT、Paint.Align.CENTER、Paint.Align.RIGHT。根据对齐方式传递到Canvas.drawText()方法。标准的对齐方式是Paint.Align.LEFT。
Paint类还有一种方法可以设置字符串边界:
Paint.setTextBounds(String test, int start, int end, Rect bounds);
第二个参数和第三个参数指定进行度量的字符串的开始字符和结束字符。最后一个参数是一个Rect实例,该方法将把边框矩形的宽度和高度写进Rect.right和Rect.bottom这两个字段。为了方便,我们调用Rect.width()和Rect.height()来获得同样的值。
下面是测试代码:
package org.example.ch04_Android_basics;
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){
paint.setColor(Color.YELLOW);
paint.setTypeface(font);
paint.setTextSize(28);
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.CYAN);
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
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(new RenderView(this));
}
}
运行效果: