自定义View—实现滚动TextView(跑马灯)效果

一般来说,自定义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呢,看下图就可以明白:

FontMetrics

如果传入的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

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值