在自定义View的时候,绘制文字往往需要我们测量出文字的宽高值。以此宽高值,我们才能绘制相应的文字。于是,记录一下经常使用的几种方法。
measureText
Return the width of the text
利用Paint的measureText()方法可以轻松的测量出文字的宽的。当然,measureText()有好四个重载方法,可以根据需要使用。
|
|
getTextBounds()
Return in bounds (allocated by the caller) the smallest rectangle that encloses all of the characters, with an implied origin at (0,0)
返回边界(由调用者分配)包含所有字符的最小矩形,隐含原点(0,0)
这一方法也是Paint中的,获得文本所在矩形区域,从而得到文本的宽高。
|
|
getFontMetrics & getFontMetricsInt
两者类似,只是返回的经度不同。前者float,后者int。
FontMetrics其中定义了五个成员变量:
ascent
The recommended distance above the baseline for singled spaced text.bottom
The maximum distance below the baseline for the lowest glyph in the font at a given text size.descent
The recommended distance below the baseline for singled spaced text.leading
The recommended additional space to add between lines of text.top
The maximum distance above the baseline for the tallest glyph in the font at a given text size.
ascent和descent是一对,以baseLine为基础,baseLine以上到字符最高处为ascent,到最低出则为descent。
top和bottom是一对,以baseLine为基础,baseLine以上到字符最高处为top,到最低出则为bottom。只不过,top和bottom还要包含一些预留的内边距。所以,通常,top值要比ascent大、bottom值要比descent大。
leading是两行文字之间的行间距。即上一行的descent到下一行的ascent的距离。
更详细的,请参考:
Android字符串进阶之三:字体属性及测量(FontMetrics)
所以,一下就是获得文本的高度:
|
|
getTextWidths()
Return the advance widths for the characters in the string
这个方法返回的是单个字符的宽度,所以这种方法应该是最精确的了。
|
|
Layout.getDesiredWidth()
Return how wide a layout must be in order to display the specified
text with one line per paragraph
TextPaint textPaint = new TextPaint();
paint.setTextSize(size);//设置字体大小
paint.setTypeface(Typeface.xx);//设置字体
float width = Layout.getDesiredWidth(str,textPaint);