要在其他平台實現自定義字體可謂是相當的麻煩,但是在Android平台就很簡單了。
首先將自定義字體ttf放到“assets”下面被實例化之后再使用。
Typeface.createFromAsset(getContext().getAssets(),"fonts/samplefont.ttf");
1 package com.yarin.android.Typefaces; 2 3 4 5 import android.app.Activity; 6 7 import android.content.Context; 8 9 import android.graphics.Canvas; 10 11 import android.graphics.Color; 12 13 import android.graphics.Paint; 14 15 import android.graphics.Typeface; 16 17 import android.os.Bundle; 18 19 import android.view.View; 20 21 22 23 public class Typefaces extends Activity 24 25 { 26 27 /** Called when the activity is first created. */ 28 29 @Override 30 31 public void onCreate(Bundle savedInstanceState) 32 33 { 34 35 super.onCreate(savedInstanceState); 36 37 38 39 setContentView(new SampleView(this)); 40 41 } 42 43 44 45 private static class SampleView extends View 46 47 { 48 49 private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 50 51 private Typeface mFace; 52 53 54 55 public SampleView(Context context) 56 57 { 58 59 super(context); 60 61 //實例化自定義字體 62 63 mFace = Typeface.createFromAsset(getContext().getAssets(),"fonts/samplefont.ttf"); 64 65 //設置字體大小 66 67 mPaint.setTextSize(32); 68 69 } 70 71 72 73 @Override protected void onDraw(Canvas canvas) 74 75 { 76 77 canvas.drawColor(Color.WHITE); 78 79 //繪制默認字體 80 81 mPaint.setTypeface(null); 82 83 canvas.drawText("Default:abcdefg", 10, 100, mPaint); 84 85 //繪制自定義字體 86 87 mPaint.setTypeface(mFace); 88 89 canvas.drawText("Custom:abcdefg", 10, 200, mPaint); 90 91 } 92 93 } 94 95 }
好了,就這么簡單就實現了自定義字體。
下面是兩個非常有用的方法,在這里備份一下:
- //消除鋸齒
- paint.setFlags(Paint.ANTI_ALIAS_FLAG)
- //取得字符串寬度
- paint.measureText()