久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

Android自定義跑馬燈文字效果

瀏覽:104日期:2022-09-26 18:29:54

本文實例為大家分享了Android自定義跑馬燈文字的具體代碼,供大家參考,具體內容如下

Android 跑馬燈效果文字:

效果圖(真實動畫很流暢,這個轉gif有問題,感覺有點卡):

Android自定義跑馬燈文字效果

代碼:

/** * 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(); }}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Android
相關文章:
主站蜘蛛池模板: 台南县| 城口县| 沈丘县| 淮安市| 遵义县| 永春县| 西乡县| 巢湖市| 白沙| 赣州市| 东至县| 淮阳县| 城口县| 五华县| 三门县| 旌德县| 景洪市| 广宗县| 鹤庆县| 丹阳市| 名山县| 绥芬河市| 马鞍山市| 凤城市| 新绛县| 晋中市| 巧家县| 娱乐| 丹巴县| 阿拉善右旗| 云龙县| 达拉特旗| 马关县| 平和县| 平利县| 大宁县| 闻喜县| 西充县| 太仓市| 陆川县| 隆子县|