Android使用自定义字体(自定义view)

要在其他平台实现自定义字体可谓是相当的麻烦,但是在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 }  

好了,就这么简单就实现了自定义字体。

下面是两个非常有用的方法,在这里备份一下:    

  1. //消除锯齿  
  2. paint.setFlags(Paint.ANTI_ALIAS_FLAG)  
  3. //取得字符串宽度  
  4. paint.measureText()  
posted @ 2018-09-13 15:14  HelloStudio  阅读(1906)  评论(0编辑  收藏  举报