自定义View绘制字符串

 1 import android.app.Activity;  
 2 import android.os.Bundle;  
 3 import android.view.Display;  
 4 import android.view.View;  
 5 import android.content.Context;  
 6 import android.graphics.Canvas;  
 7 import android.graphics.Color;  
 8 import android.graphics.Paint;  
 9 import android.graphics.Paint.FontMetrics;  
10 
11 
12 public class MainActivity extends Activity {  
13       
14     public int nScreenWidth = 0;  
15     public int nScreenHeight = 0;  
16     Paint paint = null;  
17       
18     @Override  
19     protected void onCreate(Bundle savedInstanceState) {  
20   
21         //  获取屏幕宽高  
22         Display display = getWindowManager().getDefaultDisplay();  
23         nScreenWidth = display.getWidth();  
24         nScreenHeight = display.getHeight();  
25           
26         super.onCreate(savedInstanceState);  
27         setContentView(new FontView(this));  
28     }  
29       
30     //  自定义的View  
31     class FontView extends View {  
32         public final static String STR_WIDTH = "获取字符宽度为:";  
33         public final static String STR_HEIGHT = "获取字符高度为:";  
34   
35         public FontView(Context context) {  
36             super(context);  
37             // TODO Auto-generated constructor stub  
38             paint = new Paint();  
39         }  
40           
41         @Override  
42         protected void onDraw(Canvas canvas) {  
43             super.onDraw(canvas);  
44             //  设置背景色  
45             setBackgroundColor(Color.BLACK);  
46               
47             //  设置字符串颜色  
48             paint.setColor(Color.WHITE);  
49             canvas.drawText("当前屏幕宽"+nScreenWidth, 0, 30, paint);  
50             canvas.drawText("当前屏幕高"+nScreenHeight, 0, 60, paint);  
51               
52             //  设置字体大小  
53             paint.setColor(Color.RED);  
54             paint.setTextSize(18);  
55             canvas.drawText("字体大小为18", 0, 90, paint);  
56               
57             //  消除字体锯齿  
58             paint.setFlags(Paint.ANTI_ALIAS_FLAG);  
59             canvas.drawText("消除字体锯齿", 0, 120, paint);  
60               
61             //  获取字符串宽度  
62             canvas.drawText(STR_WIDTH + getStringWidth(STR_WIDTH), 0, 150, paint);  
63               
64             //  获取字体高度  
65             canvas.drawText(STR_HEIGHT + getFontHeight() , 0, 180, paint);  
66               
67         }  
68           
69         //  获取字体串宽度  
70         private int getStringWidth(String str) {  
71             return (int) paint.measureText(str);  
72         }  
73           
74         //  获取字体高度  
75         private int getFontHeight() {  
76             FontMetrics fm = paint.getFontMetrics();  
77             return (int) Math.ceil(fm.descent - fm.top) + 2;  
78         }  
79     }  
80 }  

原文地址:https://www.cnblogs.com/androidsj/p/4422145.html