TextView 垂直居中

这里写图片描述 
需要区分的是这里的top,bottom,ascent,descent,baseline是指字内容的属性,通过getPaint().getFontMetricsInt()来获取得到。和字体内容的外部容器的属性要区分开来。

一个小测试

我自定义了一个MyTextView:

 @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        Ln.e("font bottom:" + getPaint().getFontMetricsInt().bottom +
                "  
descent:" + getPaint().getFontMetricsInt().descent +
                " 
ascent:" + getPaint().getFontMetricsInt().ascent +
                " 
top:" + getPaint().getFontMetricsInt().top +
                " 
baseline:" + getBaseline());

        /**
         * TextView组件的属性
         */
        Ln.e("textview bottom:" + getBottom() +
                " 
top:" + getTop() +
                " 
baseline:" + 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

原文地址:https://www.cnblogs.com/kelina2mark/p/7675557.html