美文网首页
自定义跑马灯 View,可循环滚动,设置是否滚动,无论内容是否满

自定义跑马灯 View,可循环滚动,设置是否滚动,无论内容是否满

作者: eagle006 | 来源:发表于2017-12-18 17:29 被阅读0次

    本文出自简书:eagle006,如需转载请标明出处,尊重原创谢谢

    博客地址:http://www.jianshu.com/p/8bc1fb4b880d

    classStrongMarqueeViewextendsTextView {

    privateRectmRect;

    private booleanmIsEnd;

    private booleanmIsEnableScroll;

    privateStringmText;

    private floatoffX;

    privatePaintmPaint;

    private intmStep=3;

    publicStrongMarqueeView(Context context) {

    super(context);

    init();

    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)

    publicStrongMarqueeView(Context context,@NullableAttributeSet attrs,intdefStyleAttr,intdefStyleRes) {

    super(context, attrs, defStyleAttr, defStyleRes);

    init();

    }

    publicStrongMarqueeView(Context context,@NullableAttributeSet attrs) {

    super(context, attrs);

    init();

    }

    publicStrongMarqueeView(Context context,@NullableAttributeSet attrs,intdefStyleAttr) {

    super(context, attrs, defStyleAttr);

    init();

    }

    private voidinit() {

    this.setMaxLines(1);

    mPaint=newPaint(Paint.ANTI_ALIAS_FLAG);

    }

    @Override

    public booleanisFocused() {

    return true;

    }

    public voidsetText(String text) {

    mText= text;

    mPaint.setTextSize(sp2px(14));

    mRect=newRect();

    mPaint.getTextBounds(mText,0,mText.length(),mRect);

    mIsEnd=false;

    offX=0f;

    this.mIsEnableScroll=false;

    invalidate();

    }

    public voidsetTextColor(@ColorIntintcolor) {

    mPaint.setColor(color);

    invalidate();

    }

    @Override

    protected voidonDraw(Canvas canvas) {

    floatx, y;

    if(!mIsEnd) {

    x = -offX;

    }else{

    x = getMeasuredWidth() -offX;

    }

    y = getMeasuredHeight() /2+ (-mPaint.ascent() -mPaint.descent()) /2;

    canvas.drawText(mText, x, y,mPaint);

    offX+=mStep;

    if((offX>=mRect.width() && !mIsEnd) || (offX>= getMeasuredWidth() +mRect.width() &&mIsEnd)) {

    offX=0;

    mIsEnd=true;

    }

    if(!mIsEnableScroll) {

    return;

    }

    invalidate();

    }

    public voidstartScroll(longdelayTime) {

    newHandler().postDelayed(newRunnable() {

    @Override

    public voidrun() {

    mIsEnableScroll=true;

    invalidate();

    }

    }, delayTime);

    }

    public voidstopScroll() {

    mIsEnableScroll=false;

    invalidate();

    }

    private intsp2px(intspValue) {

    final floatfontScale =this.getContext().getResources().getDisplayMetrics().scaledDensity;

    return(int) (spValue * fontScale +0.5f);

    }

    }

    相关文章

      网友评论

          本文标题:自定义跑马灯 View,可循环滚动,设置是否滚动,无论内容是否满

          本文链接:https://www.haomeiwen.com/subject/cxbmwxtx.html