android测量文字的宽高

获取文字高度:

int textHeight = (int) (mPaint.descent()-mPaint.ascent());

这里写图片描述
1.基准线是baseline
2.ascent:字体在baseline上方被推荐的距离(一些字体制作商需要参考这个)
3.descent:字体在是baseline下方被推荐的距离(一些字体制作商需要参考这个)
4.top:ascent的最大值
5.bottom:descent的最大值

//四个值的源码:

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;  
}

获取文字宽度:

Paint提供了下面4个重载方法,返回文本的宽度,类型是float

public float measureText(String text)
public float measureText(char[] text, int index, int count)
public float measureText(String text, int start, int end)
public float measureText(CharSequence text, int start, int end)

或者使用Paint.getTextBounds方法直接获取宽高:

 public void getTextBounds(String text, int start, int end, Rect bounds) {
        throw new RuntimeException("Stub!");
    }
String test = "QinShiMingYue";
Rect rect = new Rect();
mPaint.getTextBounds(text, 0, test.length(), rect);
int width = rect.width();//文字宽
int height = rect.height();//文字高

你可能感兴趣的:(android,字体)