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

自定義 View 實作鐘擺效果進度條 PendulumView

編輯:關於 Android 程式設計

之前在網路上看到一個 iOS 元件 PendulumView,做出了鐘擺擺動的動畫效果。由於原生進度條的外觀實在算不上好看,於是我思考能否用自定義 View 把這種效果做出來,之後也能用在載入頁面的進度提示上。

先上成果圖(底部黑邊是錄製時不小心入鏡的,可以忽略):

第一步:定義自定義屬性

建立屬性檔

在專案的 res/values 目錄下新增 attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="PendulumView">
    </declare-styleable>
</resources>

declare-styleable 的 name 用於在程式碼中引用這份屬性檔,慣例上直接寫自定義 View 的類名,最為直觀。使用 styleable 的好處是系統會自動幫我們產生 int[] 陣列與各項下標常量,例如後續用到的 R.styleable.PendulumView_globeNum,大幅簡化開發工作。

這裡定義的四個屬性分別是:globeNum(小球數量)、globeColor(小球顏色)、globeRadius(小球半徑)、swingRadius(擺動半徑)。

讀取屬性值

在自定義 View 的建構子中透過 TypedArray 取值:

public PendulumView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    TypedArray ta = context.getResources().obtainAttributes(
            attrs, R.styleable.PendulumView);
    int count = ta.getIndexCount();
    for (int i = 0; i < count; i++) {
        int attr = ta.getIndex(i);
        switch (attr) {
            case R.styleable.PendulumView_globeNum:
                mGlobeNum = ta.getInt(attr, 5);
                break;
            case R.styleable.PendulumView_globeRadius:
                mGlobeRadius = ta.getDimensionPixelSize(attr, (int) TypedValue
                        .applyDimension(TypedValue.COMPLEX_UNIT_PX, 16,
                                getResources().getDisplayMetrics()));
                break;
            case R.styleable.PendulumView_globeColor:
                mGlobeColor = ta.getColor(attr, Color.BLUE);
                break;
            case R.styleable.PendulumView_swingRadius:
                mSwingRadius = ta.getDimensionPixelSize(attr, (int) TypedValue
                        .applyDimension(TypedValue.COMPLEX_UNIT_PX, 16,
                                getResources().getDisplayMetrics()));
                break;
        }
    }
    ta.recycle();   // 記得回收,避免影響後續讀取
    mPaint = new Paint();
    mPaint.setColor(mGlobeColor);
}

雖然也可以透過 AttributeSet 取值,但若屬性是引用型別,取到的只是資源 ID,還得再解析一次才能拿到真正的值;TypedArray 直接替我們完成了這件事。

第二步:重寫 onMeasure()

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

    // 高度 = 小球半徑 + 擺動半徑
    int height = mGlobeRadius + mSwingRadius;
    // 寬度 = 2 * 擺動半徑 + (小球數量 - 1) * 小球直徑
    int width = mSwingRadius + mGlobeRadius * 2 * (mGlobeNum - 1) + mSwingRadius;

    // EXACTLY 時採用外部指定值;其他情況(多為 wrap_content)則用自算結果
    setMeasuredDimension((widthMode == MeasureSpec.EXACTLY) ? widthSize : width,
                         (heightMode == MeasureSpec.EXACTLY) ? heightSize : height);
}

這兩行計算主要處理 AT_MOST 模式,也就是自定義 View 的寬高設為 wrap_content 時,依小球數量、半徑與擺動半徑推算實際尺寸:

int height = mGlobeRadius + mSwingRadius;
int width = mSwingRadius + mGlobeRadius * 2 * (mGlobeNum - 1) + mSwingRadius;

以 5 顆小球為例,View 的範圍就是下圖的紅色矩形區域:

第三步:重寫 onDraw()

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    // 先畫出左右兩顆以外的小球
    for (int i = 0; i < mGlobeNum - 2; i++) {
        canvas.drawCircle(mSwingRadius + (i + 1) * 2 * mGlobeRadius,
                mSwingRadius, mGlobeRadius, mPaint);
    }
    if (mLeftPoint == null || mRightPoint == null) {
        // 首次繪製時初始化左右小球座標,並啟動動畫
        mLeftPoint = new Point(mSwingRadius, mSwingRadius);
        mRightPoint = new Point(
                mSwingRadius + mGlobeRadius * 2 * (mGlobeNum - 1), mSwingRadius);
        startPendulumAnimation();
    }
    canvas.drawCircle(mLeftPoint.x, mLeftPoint.y, mGlobeRadius, mPaint);
    canvas.drawCircle(mRightPoint.x, mRightPoint.y, mGlobeRadius, mPaint);
}

onDraw 是自定義 View 的關鍵所在。程式先畫出中間那些固定不動的小球,再判斷左右兩顆的座標:首次繪製時座標為空,於是初始化並啟動動畫;之後每次重繪都依 mLeftPoint、mRightPoint 的 x、y 值畫出這兩顆球。這兩個物件都是 android.graphics.Point,單純用來存放座標資訊。

第四步:用屬性動畫驅動鐘擺

public void startPendulumAnimation() {
    final ValueAnimator anim = ValueAnimator.ofObject(new TypeEvaluator() {
        @Override
        public Object evaluate(float fraction, Object startValue, Object endValue) {
            // fraction 代表動畫完成度(0~1),據此推算目前的角度與位移
            double angle = Math.toRadians(90 * fraction);
            int x = (int) ((mSwingRadius - mGlobeRadius) * Math.sin(angle));
            int y = (int) ((mSwingRadius - mGlobeRadius) * Math.cos(angle));
            return new Point(x, y);
        }
    }, new Point(), new Point());

    anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            Point point = (Point) animation.getAnimatedValue();
            float fraction = anim.getAnimatedFraction();

            // fraction 由遞減轉為遞增,代表小球即將上拋,此時切換運動的小球
            if (lastSlope && fraction > mLastFraction) {
                isNext = !isNext;
            }

            if (isNext) {
                // 左球擺動時,右球固定在初始位置
                mRightPoint.x = mSwingRadius + mGlobeRadius * 2 * (mGlobeNum - 1);
                mRightPoint.y = mSwingRadius;
                mLeftPoint.x = mSwingRadius - point.x;
                mLeftPoint.y = mGlobeRadius + point.y;
            } else {
                // 右球擺動時,左球固定在初始位置
                mLeftPoint.x = mSwingRadius;
                mLeftPoint.y = mSwingRadius;
                mRightPoint.x = mSwingRadius + (mGlobeNum - 1) * mGlobeRadius * 2 + point.x;
                mRightPoint.y = mGlobeRadius + point.y;
            }

            invalidate();
            lastSlope = fraction < mLastFraction;
            mLastFraction = fraction;
        }
    });

    anim.setRepeatCount(ValueAnimator.INFINITE);
    anim.setRepeatMode(ValueAnimator.REVERSE);
    anim.setDuration(200);
    anim.setInterpolator(new DecelerateInterpolator());
    anim.start();
}

為什麼用 ofObject

使用 ValueAnimator.ofObject 是為了能直接操作 Point 物件,語意更貼近「座標在動」這件事。同時透過自定義的 TypeEvaluator 取得了 fraction——一個從 0 到 1 變化的比率。因此後兩個參數 startValue、endValue(此處都是 new Point())其實沒有實際意義,寫上純粹是為了便於理解;同樣的效果也可以直接用 ValueAnimator.ofFloat(0f, 1f) 取得。

位移的數學推導

double angle = Math.toRadians(90 * fraction);
int x = (int) ((mSwingRadius - mGlobeRadius) * Math.sin(angle));
int y = (int) ((mSwingRadius - mGlobeRadius) * Math.cos(angle));

透過 fraction 換算出 0 到 90 度的擺動角度:

mSwingRadius - mGlobeRadius 就是圖中綠色線段的長度,也就是小球圓心實際行走的軌跡半徑。小球圓心沿著一段圆弧移動,因此 x 的變化量為 (mSwingRadius - mGlobeRadius) × sin(angle),y 的變化量為 (mSwingRadius - mGlobeRadius) × cos(angle)。

換算後,左邊小球實際的圓心座標為(mSwingRadius - x,mGlobeRadius + y);右邊小球的軌跡形狀相同,只是方向相反,座標為(mSwingRadius + (mGlobeNum - 1) × mGlobeRadius × 2 + x,mGlobeRadius + y)。可見兩側小球的縱座標完全一致,只有橫座標不同。

如何決定切換的時機

float fraction = anim.getAnimatedFraction();
// 判斷 fraction 是否由遞減轉為遞增,即小球即將上拋
if (lastSlope && fraction > mLastFraction) {
    isNext = !isNext;
}
// 記錄上一次 fraction 是否在不斷遞減
lastSlope = fraction < mLastFraction;
mLastFraction = fraction;

動畫設為循環播放且模式為 REVERSE,因此一個週期就是「上拋 + 落下」的過程,fraction 會由 0 增到 1、再由 1 減回 0。新一輪週期的起點,正是小球即將被拋起的時刻——此時切換運動主體,就能形成「左球落下後右球上拋、右球落下後左球上拋」的連續效果。

要捕捉這個瞬間並不難:小球上拋時 fraction 持續增大,落下時持續減小,因此「即將拋起」就等同於 fraction 從遞減翻轉為遞增的那一刻。程式記錄上一次是否處於遞減狀態,再比對這次是否轉為遞增,兩個條件同時成立便切換。

收尾設定

anim.setDuration(200);
anim.setInterpolator(new DecelerateInterpolator());
anim.start();

duration 設為 200 毫秒,想調整擺動快慢只要改這個值。補間器方面,小球上拋是逐漸減速、落下是逐漸加速,因此使用 DecelerateInterpolator 來模擬減速,在 REVERSE 播放時自然呈現相反的加速效果。

啟動動畫,鐘擺風格的進度條自定義 View 就完成了,快跑起來看看實際效果吧。若內容有任何疏漏之處,還請不吝指正。

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