須要區分的是這裏的top,bottom,ascent,descent,baseline是指字內容的屬性,經過getPaint().getFontMetricsInt()來獲取獲得。和字體內容的外部容器的屬性要區分開來。canvas
我自定義了一個MyTextView:ide
@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,而且實現字內容可以垂直居中,咱們在畫布中繪製文本的時候,會調用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.spa
轉載http://blog.csdn.net/xude1985/article/details/51532949.net