需要區分的是這里的top,bottom,ascent,descent,baseline是指字內容的屬性,通過getPaint().getFontMetricsInt()來獲取得到。和字體內容的外部容器的屬性要區分開來。
一個小測試
我自定義了一個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()); }
結果是:
font bottom:16 descent:14 ascent:-52 top:-60 baseline:60 textview bottom:76 top:0 baseline:60
可以總結:
- 字內容的坐標系和TextView組件的坐標系是不一樣的
- 字內容是以其父容器的baseline為原點的。
如果我們想自己實現一個TextView,並且實現字內容能夠垂直居中,我們在畫布中繪制文本的時候,會調用Canvas.drawText(String text, float x, float y, Paint paint)這個方法,其中y的坐標就是上圖中baseline的y坐標,所以,如果我們只是簡單地把drawText方法中的y設置為控件高度的1/2是不准確的。實際上:
yBaseline = Height/2 + (fontbottom-fontTop)/2 - fontBotton
看,這個時候就體現出以baseline為原點的好處了,因為我們在drawText的時候,都是需要輸入字內容的baseline 的y坐標的。而不是bottom.
轉載http://blog.csdn.net/xude1985/article/details/51532949