当前位置:网站首页>Pathmeasure implements loading animation

Pathmeasure implements loading animation

2022-07-01 03:26:00 Xiao Er Li

design sketch

 Please add a picture description

PathLoadingView.java

public class PathLoadingView extends View {
    

    private Path mPath;
    private Path dest;
    private Paint mPaint;

    private PathMeasure mPathMeasure;

    private float mLength;
    private float mAnimatedValue;

    public PathLoadingView(Context context) {
    
        this(context, null);
    }

    public PathLoadingView(Context context, @Nullable AttributeSet attrs) {
    
        this(context, attrs, 0);
    }

    public PathLoadingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    
        super(context, attrs, defStyleAttr);

        init();
    }

    private void init() {
    
        //  Initialize brush 
        mPaint = new Paint();
        mPaint.setColor(Color.parseColor("#FF4081"));
        mPaint.setStrokeWidth(2f);
        mPaint.setStyle(Paint.Style.STROKE);

        mPath = new Path();
        mPath.addCircle(300f, 300f, 20f, Path.Direction.CW);

        //  initialization  PathMeasure
        mPathMeasure = new PathMeasure(mPath, true);
        // Path  length 
        mLength = mPathMeasure.getLength();

        dest = new Path();

        //  Attribute animation , Monitor animation value changes , For dynamic calculation  path  length 
        ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
    
                //  Get the change of animation value 
                mAnimatedValue = (float) animation.getAnimatedValue();
                //  Trigger  onDraw
                invalidate();
            }
        });
        animator.setDuration(2000);
        animator.setRepeatCount(ValueAnimator.INFINITE); //  Infinite loop 
        animator.start();
    }

    @Override
    protected void onDraw(Canvas canvas) {
    
        super.onDraw(canvas);

        //  Reset before each painting  dest
        dest.reset();

        float distance = mLength * mAnimatedValue;
        // distance - 0.5*mLength < start < distance
        float start = (float) (distance - (0.5 - Math.abs(mAnimatedValue - 0.5f)) * mLength);
        //  Intercept  path  Length to  dest
        mPathMeasure.getSegment(start,distance,dest,true);
        canvas.drawPath(dest,mPaint);
    }
}

原网站

版权声明
本文为[Xiao Er Li]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202160337041422.html