自定义动画线
public class BufferLineView extends View {
public BufferLineView(Context context) {
this(context, null);
}
public BufferLineView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public BufferLineView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private int bgColor = Color.TRANSPARENT;
private Paint mLinePaint;
private int mWidth;
private int mStartSpace = 200;
private int mOffset = 0;
private ValueAnimator valueAnimator;
private boolean endFlag = false;
private void init() {
mLinePaint = new Paint();
mLinePaint.setColor(bgColor);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
mWidth = Math.max(MeasureSpec.getSize(widthMeasureSpec), 1);
int mHeight = MeasureSpec.getSize(heightMeasureSpec);
mStartSpace = mWidth / 2;
mOffset = mStartSpace / 20;
mLinePaint.setStrokeWidth(mHeight);
}
public void startAnimate() {
if (valueAnimator == null) {
valueAnimator = new ValueAnimator();
valueAnimator.setIntValues(mStartSpace, mOffset);
valueAnimator.setDuration(800);
valueAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
valueAnimator.setRepeatCount(ValueAnimator.INFINITE);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mStartSpace = (int) animation.getAnimatedValue();
if (endFlag && mStartSpace < mOffset + 10) {
valueAnimator.cancel();
return;
}
invalidate();
}
});
valueAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
// 隐藏线条
mLinePaint.setColor(bgColor);
invalidate();
}
});
}
if (valueAnimator.isRunning()) {
return;
}
endFlag = false;
valueAnimator.start();
}
public void endAnimate() {
endFlag = true;
}
public void destroy() {
endFlag = false;
if (valueAnimator != null) {
valueAnimator.removeAllUpdateListeners();
valueAnimator.removeAllListeners();
valueAnimator.cancel();
valueAnimator = null;
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int alpha = (int) (mStartSpace * 2.0f / mWidth * 225);
int statusColor = calculateStatusColor(alpha);
mLinePaint.setColor(statusColor);
canvas.drawLine(mStartSpace, 0, mWidth - mStartSpace, 0, mLinePaint);
}
public int calculateStatusColor(@IntRange(from = 0, to = 225) int alpha) {
return Color.argb(alpha, 248, 248, 255);
}
}
网友评论