最近的項目中,需要用到自定義控件。有個組件要獲取繪制文本的高度,翻開TextView 的源碼,有個方法 getLineHeight()
public int getLineHeight() { return FastMath.round(mTextPaint.getFontMetricsInt(null) * mSpacingMult + mSpacingAdd); }
getLineHeight 的注釋如下:
/** * @return the height of one standard line in pixels. Note that markup * within the text can cause individual lines to be taller or shorter * than this height, and the layout may contain additional first- * or last-line padding. */ 返回一行的高度。注意標記內的文本可能高於或低於這個高度,布局可能包含額外的第一行或最后一行填充的部分。
我們只是獲取一行文字的高度,不計算間距。
所以使用 FastMath.round( mTextPaint.getFontMetricsInt(null) ) 即可。
在網上也找到了一些通過其他辦法,獲取文本高度方式。在測試之后,發現使用上述方法,取到的高度最精確。測試的代碼就不貼了。。