Android 自定义跑马灯文字
生活随笔
收集整理的這篇文章主要介紹了
Android 自定义跑马灯文字
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Android 跑馬燈效果文字:
效果圖(真實動畫很流暢,這個轉gif有問題,感覺有點卡):
、
?
代碼:
/*** 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;}@Overridepublic void setTextColor(int color) {super.setTextColor(color);paint.setColor(color);start();}@Overridepublic 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();}@Overridepublic 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();} }?
總結
以上是生活随笔為你收集整理的Android 自定义跑马灯文字的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Scipy_常用统计函数
- 下一篇: m8+android固件,M8完美And