须要区分的是这里的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