一般来说,自定义View需要以下四个步骤:
- 自定义View的属性
- 在View的构造方法中获得自定义的属性
- 重写onMeasure方法
- 重写onDraw方法
顾名思义,onMeasure方法是测量View的大小,而onDraw方法是绘制View。
先说下我们今天的目标,实现的是滚动的TextView,并且可以设置滚动的速度。值得高兴的是,实现这个功能只需要第四个步骤,,因此,实现起来比较简单,继承TextView,并且重写onDraw方法。
关于drawText方法
在Android中绘制字符串需要用到drawText方法:
drawText(String text, float x, float y, Paint paint)
text和paint就无须解释了,x和y是绘制的起点坐标。刚刚开始接触这个函数时,我是这样用的:
canvas.drawText(mText, 0, getMeasuredHeight() / 2, mPaint);
我们可以看到字符串偏上了,查阅资料发现drawText是以baseline为基准的,什么是baseline呢,看下图就可以明白:
如果传入的y为getMeasuredHeight() / 2的话,字就会整体偏上。因此我们需要用到Paint.FontMetrics,Paint.FontMetrics可以根据字体的大小获得对应的top,ascent,descent,bottom的值,我们可以依次算出baseLine的值。
官方文档:
ascent:The recommended distance above the baseline for singled spaced text.
descent:The recommended distance below the baseline for singled spaced text.
top: The maximum distance above the baseline for the tallest glyph in the font at a given text size.
bottom:The maximum distance below the baseline for the lowest glyph in the font at a given text size.
ascent指的是baseLine到字符串顶端的距离,为负值;descent指的是baseLine到字符串底端的距离,为正值。运算时要注意正负。
因此 ( -ascent-descent )/2 是baseLine到center的距离,所以( -ascent-descent )/2+getMeasuredHeight() / 2 才应该是正确的y值,这里不明白的可以拿笔画下上面图&#x