我的Android笔记(2)--利用FontMetrics获取文本字符串的宽高 实现水平居中 垂直居中

来源:互联网 发布:h5页面设计软件 编辑:程序博客网 时间:2024/05/16 08:52

本文内容部分来自网络

字体的几个参数 ,以Android API文档定义为准,见下图

要点如下:

1. 基准点是baseline

2. Ascent是baseline之上至字符最高处的距离

3. Descent是baseline之下至字符最低处的距离

4. Leading文档说的很含糊,其实是上一行字符的descent到下一行的ascent之间的距离

5. Top指的是指的是最高字符到baseline的值,即ascent的最大值

6. 同上,bottom指的是最下字符到baseline的值,即descent的最大值


 

为了帮助理解,我特此搜索了不同的示意图。对照示意图,会很容易理解FontMetrics的参数。

pic-1

 

pic-2

 

pic-3

 

pic-4

 

pic-5

pic-6

实例

利用paint或者textpaint获取FontMetrics对象

FontMetrics fontMetrics = textPaint.getFontMetrics(); 

        String text = "asdfghjkl"; 


<span style="white-space:pre"></span>float baseX = 0;         float baseY = 100;         float topY = baseY + fontMetrics.top;         float ascentY = baseY + fontMetrics.ascent;         float descentY = baseY + fontMetrics.descent;         float bottomY = baseY + fontMetrics.bottom;         float leading = baseY + fontMetrics.leading;
以下为我个人方法

<span style="white-space:pre"><span style="color: rgb(85, 85, 85); font-family: 宋体, 'Arial Narrow', arial, serif; font-size: 14px; line-height: 28px;">FontMetrics </span></span>f = paint.getFontMetrics();paint.setTextSize(20);textHeight =Math.abs( f.ascent + f.descent + f.leading);// 获取文本高度(有时为负值,这里取正值)textWidth = paint.measureText(drawtext);<span style="font-family: 宋体, 'Arial Narrow', arial, serif;">// 获取文本宽度</span>
这样在自定义view或者surfaceView中可以设置文本水平居中和垂直居中了。

0 0
原创粉丝点击