Android自定義跑馬燈文字效果
本文實(shí)例為大家分享了Android自定義跑馬燈文字的具體代碼,供大家參考,具體內(nèi)容如下
Android 跑馬燈效果文字:
效果圖(真實(shí)動(dòng)畫(huà)很流暢,這個(gè)轉(zhuǎn)gif有問(wèn)題,感覺(jué)有點(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;// 是否開(kāi)始滾動(dòng) private Paint paint = null; private String text = ''; private long waitTime = 1000; //開(kāi)始時(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. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說(shuō)明2. CSS hack用法案例詳解3. ASP 處理JSON數(shù)據(jù)的實(shí)現(xiàn)代碼4. PHP設(shè)計(jì)模式中工廠模式深入詳解5. 用css截取字符的幾種方法詳解(css排版隱藏溢出文本)6. asp中response.write("中文")或者js中文亂碼問(wèn)題7. 將properties文件的配置設(shè)置為整個(gè)Web應(yīng)用的全局變量實(shí)現(xiàn)方法8. ThinkPHP5實(shí)現(xiàn)JWT Token認(rèn)證的過(guò)程(親測(cè)可用)9. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向10. jsp網(wǎng)頁(yè)實(shí)現(xiàn)貪吃蛇小游戲
