亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Android自定義跑馬燈文字效果

 更新時間:2020年03月11日 10:27:12   作者:廣靚  
這篇文章主要為大家詳細介紹了Android自定義跑馬燈文字效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

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

Android 跑馬燈效果文字:

效果圖(真實動畫很流暢,這個轉(zhuǎn)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;
  }
 
  @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;
    //判斷是否滾動結(jié)束
    if (drawTextX > textLength) {
      drawTextX = -canvas.getWidth();
 
    }
    invalidate();
  }
}

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

最新評論