要在其他平台實現自訂字型可謂是相當的麻煩,但是在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()