Android 计算字符串宽高

最近碰到一个行奇葩的需求,需要在不使用Textview的情况下获取字体的宽高。

一、字体属性

img

二、测量

2.1、使用FontMetrics获取

FontMetrics

public static class FontMetrics {
/**
* The maximum distance above the baseline for the tallest glyph in
* the font at a given text size.
*/
public float top;
/**
* The recommended distance above the baseline for singled spaced text.
*/
public float ascent;
/**
* The recommended distance below the baseline for singled spaced text.
*/
public float descent;
/**
* The maximum distance below the baseline for the lowest glyph in
* the font at a given text size.
*/
public float bottom;
/**
* The recommended additional space to add between lines of text.
*/
public float leading;
}

TextView textView = (TextView) findViewById(R.id.textView1); 
String textMultiLines = "ssssss";
textView.setTextSize(55);
textView.setText(textMultiLines);
FontMetrics fontMetrics2 = textView.getPaint().getFontMetrics();
// 宽度
Paint p = textView.getPaint();
p.setTextSize(55);
Float tw = textView.getPaint().measureText(text);
// 高度
Float tH = fontMetrics2.bottom - fontMetrics2.top;

基准点是baseline

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

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

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

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

Bottom指的是最下字符到baseline的值,即descent的最大值

2.2 使用Paint测量(不准确)

该方法无法测量设置大小的文字

Paint pFont = new Paint();
Rect rect = new Rect();
pFont.getTextBounds("豆", 0, 1, rect);

// 直接通过Rect获取,但是height不准确
Log.v(TAG, "字符串高度:"+rect.height() + "字符串宽度:"+rect.width());

// 通过descent - ascent 获取单个字符的高度
int ch = paint.getDescent() - paint.getAscent();
作者

AriaLyy

发布于

2020-08-03

许可协议

CC BY-NC-SA 4.0

评论