Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自定義 CircleProgress:三色環形載入動畫元件實作

編輯:關於 Android 程式設計

在 GitHub 上看到一個視覺效果不錯的載入動畫(CircleProgress),以下整理它的實作原理與接入步驟。這個元件用 15 個圓點沿圓周排列,透過相位差讓顏色依序遞變,形成流動的彩虹光環。

一、核心 View 程式碼

package com.hysmarthotel.view;

import com.hysmarthotel.roomcontrol.R;
import com.hysmarthotel.util.EaseInOutCubicInterpolator;

import android.animation.TimeInterpolator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AnimationUtils;

public class CircleProgress extends View {

    private static final int RED    = 0xFFE5282C;
    private static final int YELLOW = 0xFF1F909A;
    private static final int BLUE   = 0xFFFC9E12;
    private static final int COLOR_NUM = 3;

    private int[] COLORS;
    private TimeInterpolator mInterpolator = new EaseInOutCubicInterpolator();

    private final double DEGREE = Math.PI / 180;

    private Paint mPaint;
    private int mViewSize;
    private int mPointRadius;

    private long mStartTime;
    private long mPlayTime;
    private boolean mStartAnim = false;

    private Point mCenter = new Point();
    private ArcPoint[] mArcPoint;

    private static final int POINT_NUM   = 15;
    private static final int DELTA_ANGLE = 360 / POINT_NUM;
    private long mDuration = 3600;

    public CircleProgress(Context context) { super(context); init(null, 0); }
    public CircleProgress(Context context, AttributeSet attrs) { super(context, attrs); init(attrs, 0); }
    public CircleProgress(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs, defStyle);
    }

    private void init(AttributeSet attrs, int defStyle) {
        mArcPoint = new ArcPoint[POINT_NUM];
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.FILL);

        TypedArray a = getContext().obtainStyledAttributes(
                attrs, R.styleable.CircleProgress, defStyle, 0);
        int color1 = a.getColor(R.styleable.CircleProgress_color1, RED);
        int color2 = a.getColor(R.styleable.CircleProgress_color2, YELLOW);
        int color3 = a.getColor(R.styleable.CircleProgress_color3, BLUE);
        a.recycle();

        COLORS = new int[]{ color1, color2, color3 };
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int defaultSize = getResources()
                .getDimensionPixelSize(R.dimen.default_circle_view_size);
        int width  = getDefaultSize(defaultSize, widthMeasureSpec);
        int height = getDefaultSize(defaultSize, heightMeasureSpec);
        // 取長寬的較小值,保證是正圓
        mViewSize = Math.min(width, height);
        setMeasuredDimension(mViewSize, mViewSize);
        mCenter.set(mViewSize / 2, mViewSize / 2);
        calPoints(1.0f);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.save();
        canvas.translate(mCenter.x, mCenter.y);
        float factor = getFactor();
        canvas.rotate(36 * factor);

        for (int i = 0; i < POINT_NUM; ++i) {
            mPaint.setColor(mArcPoint[i].color);
            float itemFactor = getItemFactor(i, factor);
            float x = mArcPoint[i].x - 2 * mArcPoint[i].x * itemFactor;
            float y = mArcPoint[i].y - 2 * mArcPoint[i].y * itemFactor;
            canvas.drawCircle(x, y, mPointRadius, mPaint);
        }
        canvas.restore();

        if (mStartAnim) {
            postInvalidate();
        }
    }

    /** 依半徑計算 15 個圓點的座標與顏色 */
    private void calPoints(float factor) {
        int radius = (int) (mViewSize / 3 * factor);
        mPointRadius = radius / 12;
        for (int i = 0; i < POINT_NUM; ++i) {
            float x = radius * -(float) Math.sin(DEGREE * DELTA_ANGLE * i);
            float y = radius * -(float) Math.cos(DEGREE * DELTA_ANGLE * i);
            mArcPoint[i] = new ArcPoint(x, y, COLORS[i % COLOR_NUM]);
        }
    }

    /** 全局動畫進度,回傳 0~1 之間循環的值 */
    private float getFactor() {
        if (mStartAnim) {
            mPlayTime = AnimationUtils.currentAnimationTimeMillis() - mStartTime;
        }
        return (mPlayTime / (float) mDuration) % 1f;
    }

    /** 每個點的相位落後量,製造由後往前的波浪效果 */
    private float getItemFactor(int index, float factor) {
        float itemFactor = (factor - 0.66f / POINT_NUM * index) * 3;
        if (itemFactor < 0f)      itemFactor = 0f;
        else if (itemFactor > 1f) itemFactor = 1f;
        return mInterpolator.getInterpolation(itemFactor);
    }

    public void startAnim() {
        mPlayTime = mPlayTime % mDuration;
        mStartTime = AnimationUtils.currentAnimationTimeMillis() - mPlayTime;
        mStartAnim = true;
        postInvalidate();
    }

    public void stopAnim() { mStartAnim = false; }

    public void reset() {
        stopAnim();
        mPlayTime = 0;
        postInvalidate();
    }

    public void setInterpolator(TimeInterpolator interpolator) { mInterpolator = interpolator; }
    public void setDuration(long duration) { mDuration = duration; }

    public void setRadius(float factor) {
        stopAnim();
        calPoints(factor);
        startAnim();
    }

    static class ArcPoint {
        float x;
        float y;
        int color;
        ArcPoint(float x, float y, int color) {
            this.x = x;
            this.y = y;
            this.color = color;
        }
    }
}

二、三次插值器

package com.hysmarthotel.util;

import android.animation.TimeInterpolator;

public class EaseInOutCubicInterpolator implements TimeInterpolator {
    @Override
    public float getInterpolation(float input) {
        if ((input *= 2) < 1.0f) {
            return 0.5f * input * input * input;
        }
        input -= 2;
        return 0.5f * input * input * input + 1;
    }
}

三、原理拆解

這個動畫之所以看起來「在流動」,靠的是 相位差 而非整體旋轉。三個關鍵方法各司其職:

calPoints 把 15 個點均勻分佈在圓周上,每個點的顏色依 i % 3 循環取三色之一,並預先算好三角函數座標,避免每幀重算。

getFactor 回傳全域進度,用當前時間減去起始時間再除以 mDuration,取餘確保在 0~1 之間循環。整體 canvas.rotate(36 * factor) 讓光環緩慢自轉。

getItemFactor 是精髓:每個點在全域進度上再減去 0.66 / POINT_NUM * index 的偏移量,並夾在 0~1 之間。這個偏移讓第 i 個點比第 0 個點「落後」一點,再乘 3 放大對比,最後交給三次插值器做緩入緩出。結果就是圓點依序縮放,形成一道繞圈跑的亮帶。

onDraw 中 x - 2 * x * itemFactor 這行讓圓點向圓心靠攏,配合半徑縮減,视觉上像是點被吸進去又彈出來。

四、在 Activity 中調用

mProgressView = (CircleProgress) findViewById(R.id.progress_vie);

mProgressView.startAnim();   // 開始
mProgressView.stopAnim();    // 停止
mProgressView.setRadius(factor);  // 調整環的半徑比例
mProgressView.reset();       // 復位

五、xml 布局

<AbsoluteLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:circleprogress="https://schemas.android.com/apk/res/com.hysmarthotel.roomcontrol"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg1" >

    <com.hysmarthotel.view.CircleProgress
        android:id="@+id/progress_vie"
        android:layout_x="350.5px"
        android:layout_y="150.0px"
        android:layout_width="1140.0px"
        android:layout_height="700.0px"
        circleprogress:color1="@android:color/holo_red_light"
        circleprogress:color2="@android:color/holo_green_light"
        circleprogress:color3="@android:color/holo_blue_light" />
</AbsoluteLayout>

這裡的命名空間 xmlns:circleprogress 後面接的是 應用包名,必須與 attrs 的宣告一致,否則自定義屬性會解析失敗。順帶一提,AbsoluteLayout 早已被標記為不建議使用,實作時建議換成 ConstraintLayout 或 FrameLayout。

六、自定義屬性宣告

在 res/values/attrs.xml:

<declare-styleable name="CircleProgress">
    <attr name="color1" format="reference|color"/>
    <attr name="color2" format="reference|color"/>
    <attr name="color3" format="reference|color"/>
</declare-styleable>

在 res/values/dimens.xml:

<resources>
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="default_circle_view_size">200dp</dimen>
</resources>

七、小結

這個元件示範了自定義 View 的幾個常用套路:onMeasure 中取長寬最小值保持正圓、在構造階段預先計算靜態幾何資料、用「全域進度 + 逐項相位偏移」製造波浪、以及用 postInvalidate 驅動逐幀重繪。把相位偏移的係數(0.66f)和放大倍率(* 3)當成可調參數,就能玩出不同節奏的效果。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved