本文出自简书: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);
}
}