![复制代码](//assets.cnblogs.com/images/copycode.gif)
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 }
![复制代码](//assets.cnblogs.com/images/copycode.gif)
![](//images0.cnblogs.com/blog2015/376754/201504/131442486987635.jpg)
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· 手把手教你更优雅的享受 DeepSeek
· AI工具推荐:领先的开源 AI 代码助手——Continue
· 探秘Transformer系列之(2)---总体架构
· V-Control:一个基于 .NET MAUI 的开箱即用的UI组件库
· 乌龟冬眠箱湿度监控系统和AI辅助建议功能的实现