本文实例为大家分享了Android自定义跑马灯文字的具体代码,供大家参考,具体内容如下
Android 跑马灯效果文字:
效果图(真实动画很流畅,这个转gif有问题,感觉有点卡):
代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
|
/** * Created by wuguangliang on 2018/12/21 * * 跑马灯效果文字 */ public class MarqueeHorizontalTextView extends AppCompatTextView { private float textLength = 0f; private float drawTextX = 0f; // 文本的横坐标 public boolean isStarting = false ; // 是否开始滚动 private Paint paint = null ; private String text = "" ; private long waitTime = 1000 ; //开始时等待的时间 private int scrollTile = 2 ; //文字的滚动速度 private int baseline; public MarqueeHorizontalTextView(Context context) { super (context); initView(context); } public MarqueeHorizontalTextView(Context context, AttributeSet attrs) { super (context, attrs); initView(context); } public MarqueeHorizontalTextView(Context context, AttributeSet attrs, int defStyle) { super (context, attrs, defStyle); initView(context); } private void initView(Context context) { setMaxWidth(context.getResources().getDisplayMetrics().widthPixels / 2 ); //因为需求需要所以设置了最大宽度,如果不需要此功能可以删除掉 paint = getPaint(); paint.setColor(getTextColors().getColorForState(getDrawableState(), 0 )); text = getText().toString(); if (TextUtils.isEmpty(text)) { return ; } textLength = paint.measureText(text); isStarting = true ; } @Override public void setTextColor( int color) { super .setTextColor(color); paint.setColor(color); start(); } @Override public void setText(CharSequence text, BufferType type) { super .setText(text, type); this .text = text.toString(); this .textLength = getPaint().measureText(text.toString()); drawTextX = 0 ; start(); } public void start() { isStarting = true ; invalidate(); } public void stop() { isStarting = false ; invalidate(); } @Override public void onDraw(Canvas canvas) { final Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt(); baseline = (canvas.getHeight() - fontMetrics.bottom - fontMetrics.top) / 2 ; if (textLength <= canvas.getWidth()) { canvas.drawText(text, 0 , baseline, paint); return ; } canvas.drawText(text, -drawTextX, baseline, paint); if (!isStarting) { return ; } if (drawTextX == 0 ) { postDelayed(() -> { drawTextX = 1 ; isStarting = true ; invalidate(); }, waitTime); isStarting = false ; return ; } drawTextX += scrollTile; //判断是否滚动结束 if (drawTextX > textLength) { drawTextX = -canvas.getWidth(); } invalidate(); } } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/guang_liang_/article/details/85159375