一圖以蔽之
需要區(qū)分的是這里的top,bottom输虱,ascent摘能,descent站刑,baseline是指字內(nèi)容的屬性另伍,通過getPaint().getFontMetricsInt()來獲取得到。和字體內(nèi)容的外部容器的屬性要區(qū)分開來绞旅。
一個小測試
我自定義了一個MyTextView:
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Ln.e("font bottom:" + getPaint().getFontMetricsInt().bottom +
" \ndescent:" + getPaint().getFontMetricsInt().descent +
" \nascent:" + getPaint().getFontMetricsInt().ascent +
" \ntop:" + getPaint().getFontMetricsInt().top +
" \nbaseline:" + getBaseline());
/**
* TextView組件的屬性
*/
Ln.e("textview bottom:" + getBottom() +
" \ntop:" + getTop() +
" \nbaseline:" + getBaseline());
}
結(jié)果是:
font bottom:16
descent:14
ascent:-52
top:-60
baseline:60
textview bottom:76
top:0
baseline:60
有此可知:(向下為正值摆尝,向上為負值)
1 getBaseline()得到的是baseline相對于textview的位置
2 getFontMetricsInt().bottom得到的是文字底部(帶邊距)相對于base向下的距離
3 getFontMetricsInt().top得到的事文字頂部(帶邊距)相對于base向上的距離
4 getFontMetricsInt().descent得到的是文字底部(不帶邊距)相對于base向下的距離
5 getFontMetricsInt().ascent得到的事文字頂部(不帶邊距)相對于base向上的距離
可以總結(jié):
- 字內(nèi)容的坐標系和TextView組件的坐標系是不一樣的
- 字內(nèi)容是以其父容器的baseline為原點的。
如果我們想自己實現(xiàn)一個TextView,并且實現(xiàn)字內(nèi)容能夠垂直居中玻靡,我們在畫布中繪制文本的時候,會調(diào)用Canvas.drawText(String text, float x, float y, Paint paint)這個方法中贝,其中<u style="box-sizing: border-box;">y的坐標就是上圖中baseline的y坐標</u>囤捻,所以,如果我們只是簡單地把drawText方法中的y設(shè)置為控件高度的1/2是不準確的邻寿。實際上:
yBaseline = Height/2 + (fontbottom-fontTop)/2 - fontBotton
看蝎土,這個時候就體現(xiàn)出以baseline為原點的好處了,因為我們在drawText的時候绣否,都是需要輸入字內(nèi)容的baseline 的y坐標的誊涯。而不是bottom.
所以當(dāng)我們使用Canvas的drawText方法時,對應(yīng)的y值應(yīng)該計算對應(yīng)的baseline的值