Android自定義跑馬燈文字效果
本文實(shí)例為大家分享了Android自定義跑馬燈文字的具體代碼,供大家參考,具體內(nèi)容如下
Android 跑馬燈效果文字:
效果圖(真實(shí)動(dòng)畫很流暢,這個(gè)轉(zhuǎn)gif有問題,感覺有點(diǎn)卡):
代碼:
/** * Created by wuguangliang on 2018/12/21 * * 跑馬燈效果文字 */public class MarqueeHorizontalTextView extends AppCompatTextView { private float textLength = 0f; private float drawTextX = 0f;// 文本的橫坐標(biāo) public boolean isStarting = false;// 是否開始滾動(dòng) private Paint paint = null; private String text = ''; private long waitTime = 1000; //開始時(shí)等待的時(shí)間 private int scrollTile = 2; //文字的滾動(dòng)速度 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); //因?yàn)樾枨笮枰栽O(shè)置了最大寬度,如果不需要此功能可以刪除掉 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; //判斷是否滾動(dòng)結(jié)束 if (drawTextX > textLength) { drawTextX = -canvas.getWidth(); } invalidate(); }}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. XML解析錯(cuò)誤:未組織好 的解決辦法2. jsp+servlet簡(jiǎn)單實(shí)現(xiàn)上傳文件功能(保存目錄改進(jìn))3. html中的form不提交(排除)某些input 原創(chuàng)4. 利用CSS制作3D動(dòng)畫5. jsp實(shí)現(xiàn)局部刷新頁面、異步加載頁面的方法6. 告別AJAX實(shí)現(xiàn)無刷新提交表單7. jsp實(shí)現(xiàn)登錄驗(yàn)證的過濾器8. ASP.NET Core實(shí)現(xiàn)中間件的幾種方式9. 使用css實(shí)現(xiàn)全兼容tooltip提示框10. .Net Core和RabbitMQ限制循環(huán)消費(fèi)的方法
