一個簡單的圓弧刷新動畫

  之前刷貼吧的時候看到的貼吧的刷新動畫,就是一個圓弧旋轉的動畫,感覺挺好看的,就抽空實現了一下。
最終的結果是這樣的:
在這裏插入圖片描述

  從上圖中可以看出,動畫的效果是三段圓弧進行旋轉,同時弧度也在逐漸增大縮小,這裏採用的是在onDraw中繪製三段圓弧。

		// 繪製圓弧
        mPaint.setColor(mTopColor);
        canvas.drawArc(left, top, right, bottom, startAngle, sweepAngle, false, mPaint);
        mPaint.setColor(mLeftColor);
        canvas.drawArc(left, top, right, bottom, startAngle - 120, sweepAngle, false, mPaint);
        mPaint.setColor(mRightColor);
        canvas.drawArc(left, top, right, bottom, startAngle + 120, sweepAngle, false, mPaint);

  動畫的基礎是在onDraw中,依次繪製三種不同顏色的圓弧。三段圓弧每每相隔120度,這樣就可以剛好平分整個圓,比較美觀。
  注意這裏的startAngle的初始值是 -90 ,剛好是圓的最上面一點。這裏需要注意的是canvas的drawArc方法中,前四個參數是決定圓弧的位置的矩形的座標,startAngle指的是圓弧開始的角度,0度是圓的最右側的點,以順時針爲正、逆時針爲負。所以-90度剛好是圓的最上面的點。
  sweepAngle是指圓弧掃過的角度,同樣順時針爲正,逆時針爲負。這裏sweepAngle的大小初始值是-1,這樣在動畫未開始之前也能夠繪製出一個圓點(實際上是角度爲1的圓弧,近似圓點)。
後面一個參數是useCenter,指的是是否使用圓心,爲true時就會將圓弧的兩個端點連向圓心構成一個扇形,爲false時則不會連接圓心。
  另外要注意paint的style要設置爲stroke,默認情況下是fill模式,也就是會直接填充。對於這裏的圓弧,會直接連接圓弧的兩個端點構成閉合圖形然後進行填充。
在這裏插入圖片描述
  這樣的話繪製出來的就是動畫的初始狀態:三個圓點(實際上是一段角度爲1的圓弧)。
  從上面也可以看出,要繪製圓弧必須要有四個座標,這裏的座標是以這種方式得到的:以View的長寬中最短的一邊作爲組成圓的正方形的邊長,然後居中顯示。

		int width = getMeasuredWidth();
        int height = getMeasuredHeight();
        int side = Math.min(width - getPaddingStart() - getPaddingEnd(), height - getPaddingTop() - getPaddingBottom()) - (int) (mStrokeWidth + 0.5F);

        // 確定動畫位置
        float left = (width - side) / 2F;
        float top = (height - side) / 2F;
        float right = left + side;
        float bottom = top + side;

  上面的一段代碼就是定位圓弧的正方形座標的實現,這裏可以看到在計算邊長side的時候,去掉了view的padding和mStrokenWidth。其中mStrokenWidth是圓弧的弧線的寬度,由於圓弧的線較寬的時候(此時相當於圓環)會向內外均勻延伸,也就是內邊距和外邊距的中間到圓心的距離纔是半徑。因此在確定圓弧的位置時,要去除線寬,以防止在交界處圓弧無法完全繪製。
  另外,我們自定義View時,默認的wrap_content模式下會與match_parent的效果一樣,因此需要在onMeasure中進行處理。這裏就簡單的設置wrap_content模式下爲20dp。

	@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);

        // 對於wrap_content ,設置其爲20dp。默認情況下wrap_content和match_parent是一樣的效果
        if (widthMode == MeasureSpec.AT_MOST) {
            width = (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, getContext().getResources().getDisplayMetrics()) + 0.5F);
        }
        if (heightMode == MeasureSpec.AT_MOST) {
            height = (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, getContext().getResources().getDisplayMetrics()) + 0.5F);
        }
        setMeasuredDimension(width, height);
    }

  以上的操作就是動畫的整個基礎,而讓View動起來的操作就是不斷地修改圓弧的startAngle和sweepAngle,然後觸發View的重繪。這個過程使用ValueAnimator來生成一系列數字,然後根據這個來計算圓弧的開始角度和掃描角度。

		// 最小角度爲1度,是爲了顯示小圓點
        sweepAngle = -1;
        startAngle = -90;
        curStartAngle = startAngle;

       // 擴展動畫
        mValueAnimator = ValueAnimator.ofFloat(0, 1).setDuration(mDuration);
        mValueAnimator.setRepeatMode(ValueAnimator.REVERSE);
        mValueAnimator.setRepeatCount(ValueAnimator.INFINITE);
        mValueAnimator.addUpdateListener(animation -> {
            float fraction = animation.getAnimatedFraction();
            float value = (float) animation.getAnimatedValue();
            if (mReverse)
                fraction = 1 - fraction;
            startAngle = curStartAngle + fraction * 120;
            sweepAngle = -1 - mMaxSweepAngle * value;
            postInvalidate();
        });
        mValueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationRepeat(Animator animation) {
                curStartAngle = startAngle;
                mReverse = !mReverse;
            }
        });

  上面就是計算的過程,該動畫採用的是value值從0到1再到0,對應着其中一段圓弧從原點伸展到最大再縮小回原點。其中sweepAngle的計算是 sweepAngle = -1 - mMaxSweepAngle * value ,也就是在整個過程中,圓弧的角度逐漸增大到maxSweepAngle。這裏採用的是負值,也就是從startAngle按逆時針方向進行繪製。-1是基礎值,以防止縮小到最小時也能夠顯示出一個圓點。
  startAngle的計算則是根據動畫過程的fraction,而不是動畫值,也就是從0到1,在整個動畫過程中逐漸增加120度。由於整個View是由三段相同的圓弧形成的,也就是說每段圓弧最大隻能佔據120度,否則就會重疊。那麼在0到1這個過程中,弧度增大到120度,startAngle則必須移動120度給圓弧騰出位置,這就是120度的由來。並且監聽Reverse狀態,因爲在Reverse狀態下,fraction是從1到0的,而我們需要的是startAngle一直逐漸增大,因此在Reverse下通過1-fraction使之與原動畫一致。 並且每次reverse監聽下,記錄startAngle作爲新的當前位置和記錄reverse狀態。

  以上就是整個圓弧動畫的實現細節了,整體比較簡單,就是通過對弧度的startAngle和sweepAngle進行改變然後通知View重繪。 下面是實現的完整代碼 ,這裏抽取了一些基礎變量放到屬性中,用於簡便控制動畫的顯示:

values/attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="RefreshView">
        <attr name="top_color" format="color"/>
        <attr name="left_color" format="color"/>
        <attr name="right_color" format="color"/>
        <!-- 圓弧的寬度 -->
        <attr name="border_width" format="dimension"/>
        <!-- 每個週期的時間,從點到最大弧爲一個週期,ms -->
        <attr name="duration" format="integer"/>
        <!-- 圓弧掃過的最大角度 -->
        <attr name="max_sweep_angle" format="integer"/>
        <!-- 是否自動開啓動畫 -->
        <attr name="auto_start" format="boolean"/>
    </declare-styleable>

</resources>
RefreshView.java

package com.pgaofeng.mytest.other;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;

import com.pgaofeng.mytest.R;

/**
 * @author gaofengpeng
 * @date 2019/9/16
 * @description :
 */
public class RefreshView extends View {

    /**
     * 動畫的三種顏色
     */
    private int mTopColor;
    private int mLeftColor;
    private int mRightColor;

    private Paint mPaint;

    /**
     * 掃描角度,用於控制圓弧的長度
     */
    private float sweepAngle;
    /**
     * 開始角度,用於控制圓弧的顯示位置
     */
    private float startAngle;
    /**
     * 當前角度,記錄圓弧旋轉的角度
     */
    private float curStartAngle;

    /**
     * 用動畫控制圓弧顯示
     */
    private ValueAnimator mValueAnimator;

    /**
     * 每個週期的時長
     */
    private int mDuration;
    /**
     * 圓弧線寬
     */
    private float mStrokeWidth;

    /**
     * 動畫過程中最大的圓弧角度
     */
    private int mMaxSweepAngle;

    /**
     * 是否自動開啓動畫
     */
    private boolean mAutoStart;

    /**
     * 用於判斷當前動畫是否處於Reverse狀態
     */
    private boolean mReverse = false;


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

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

    public RefreshView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttr(context, attrs);
        init();
    }

    private void initAttr(Context context, AttributeSet attrs) {
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RefreshView);
        mTopColor = array.getColor(R.styleable.RefreshView_top_color, Color.BLUE);
        mLeftColor = array.getColor(R.styleable.RefreshView_left_color, Color.YELLOW);
        mRightColor = array.getColor(R.styleable.RefreshView_right_color, Color.RED);
        mDuration = array.getInt(R.styleable.RefreshView_duration, 600);
        if (mDuration <= 0) {
            mDuration = 600;
        }
        mStrokeWidth = array.getDimension(R.styleable.RefreshView_border_width, 8F);
        mMaxSweepAngle = array.getInt(R.styleable.RefreshView_max_sweep_angle, 90);
        if (mMaxSweepAngle <= 0 || mMaxSweepAngle > 120) {
            // 對於不規範值直接採用默認值
            mMaxSweepAngle = 90;
        }
        mAutoStart = array.getBoolean(R.styleable.RefreshView_auto_start, true);

        array.recycle();
    }

    private void init() {

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(mStrokeWidth);
        mPaint.setStrokeCap(Paint.Cap.ROUND);

        // 最小角度爲1度,是爲了顯示小圓點
        sweepAngle = -1;
        startAngle = -90;
        curStartAngle = startAngle;

        // 擴展動畫
        mValueAnimator = ValueAnimator.ofFloat(0, 1).setDuration(mDuration);
        mValueAnimator.setRepeatMode(ValueAnimator.REVERSE);
        mValueAnimator.setRepeatCount(ValueAnimator.INFINITE);
        mValueAnimator.addUpdateListener(animation -> {
            float fraction = animation.getAnimatedFraction();
            float value = (float) animation.getAnimatedValue();

            if (mReverse)
                fraction = 1 - fraction;

            startAngle = curStartAngle + fraction * 120;
            sweepAngle = -1 - mMaxSweepAngle * value;
            postInvalidate();
        });
        mValueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationRepeat(Animator animation) {
                curStartAngle = startAngle;
                mReverse = !mReverse;
            }
        });

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);

        // 對於wrap_content ,設置其爲20dp。默認情況下wrap_content和match_parent是一樣的效果
        if (widthMode == MeasureSpec.AT_MOST) {
            width = (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, getContext().getResources().getDisplayMetrics()) + 0.5F);
        }
        if (heightMode == MeasureSpec.AT_MOST) {
            height = (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, getContext().getResources().getDisplayMetrics()) + 0.5F);
        }
        setMeasuredDimension(width, height);
    }

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

        int width = getMeasuredWidth();
        int height = getMeasuredHeight();

        int side = Math.min(width - getPaddingStart() - getPaddingEnd(), height - getPaddingTop() - getPaddingBottom()) - (int) (mStrokeWidth + 0.5F);

        // 確定動畫位置
        float left = (width - side) / 2F;
        float top = (height - side) / 2F;
        float right = left + side;
        float bottom = top + side;

        // 繪製圓弧
        mPaint.setColor(mTopColor);
        canvas.drawArc(left, top, right, bottom, startAngle, sweepAngle, false, mPaint);
        mPaint.setColor(mLeftColor);
        canvas.drawArc(left, top, right, bottom, startAngle - 120, sweepAngle, false, mPaint);
        mPaint.setColor(mRightColor);
        canvas.drawArc(left, top, right, bottom, startAngle + 120, sweepAngle, false, mPaint);
    }


    @Override
    protected void onDetachedFromWindow() {
        if (mAutoStart && mValueAnimator.isRunning()) {
            mValueAnimator.cancel();
        }
        super.onDetachedFromWindow();
    }

    @Override
    protected void onAttachedToWindow() {
        if (mAutoStart && !mValueAnimator.isRunning()) {
            mValueAnimator.start();
        }
        super.onAttachedToWindow();
    }

    /**
     * 開始動畫
     */
    public void start() {
        if (!mValueAnimator.isStarted()) {
            mValueAnimator.start();
        }
    }

    /**
     * 暫停動畫
     */
    public void pause() {
        if (mValueAnimator.isRunning()) {
            mValueAnimator.pause();
        }
    }

    /**
     * 繼續動畫
     */
    public void resume() {
        if (mValueAnimator.isPaused()) {
            mValueAnimator.resume();
        }
    }

    /**
     * 停止動畫
     */
    public void stop() {
        if (mValueAnimator.isStarted()) {
            mReverse = false;
            mValueAnimator.end();
        }
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章