要在其他平台实现自定义字体可谓是相当的麻烦,但是在Android平台就很简单了。
首先将自定义字体放到“assets”下面被实例化之后再使用,字体文件如下图所示。
在程序中通过如下方式实例化自定义字体:
- Typeface.createFromAsset(getContext().getAssets(),"fonts/samplefont.ttf");
下面是Android默认字体和自定义字体的绘制效果:
源代码如下:
- package com.yarin.android.Typefaces;
- import android.app.Activity;
- import android.content.Context;
- import android.graphics.Canvas;
- import android.graphics.Color;
- import android.graphics.Paint;
- import android.graphics.Typeface;
- import android.os.Bundle;
- import android.view.View;
- public class Typefaces extends Activity
- {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState)
- {
- super.onCreate(savedInstanceState);
- setContentView(new SampleView(this));
- }
- private static class SampleView extends View
- {
- private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
- private Typeface mFace;
- public SampleView(Context context)
- {
- super(context);
- //实例化自定义字体
- mFace = Typeface.createFromAsset(getContext().getAssets(),"fonts/samplefont.ttf");
- //设置字体大小
- mPaint.setTextSize(32);
- }
- @Override protected void onDraw(Canvas canvas)
- {
- canvas.drawColor(Color.WHITE);
- //绘制默认字体
- mPaint.setTypeface(null);
- canvas.drawText("Default:abcdefg", 10, 100, mPaint);
- //绘制自定义字体
- mPaint.setTypeface(mFace);
- canvas.drawText("Custom:abcdefg", 10, 200, mPaint);
- }
- }
- }
好了,就这么简单就实现了自定义字体。
下面是两个非常有用的方法,在这里备份一下:
- //消除锯齿
- paint.setFlags(Paint.ANTI_ALIAS_FLAG)
- //取得字符串宽度
- paint.measureText()
本文转自 yarin 51CTO博客,原文链接:http://blog.51cto.com/yarin/380358,如需转载请自行联系原作者