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

Android 平滑滾動原理剖析:Scroller 其實只是個座標計算器

編輯:關於 Android 程式設計

Scroller 是 Android 中用來輔助 View 平滑移動的類別。對剛接觸它的人來說,往往有兩個疑問纏身:

  1. 它到底是怎麼讓 View 動起來的(跟 View 之間是什麼關係)?
  2. 又是谁触發了它?

要回答這兩題,得從 View 的繪製流程切進去。網路上關於繪製流程的文章很多,內容大同小異,這裡只摘出理解 Scroller 必要的幾個環節:

scrollTo()/scrollBy() → invalidate()/postInvalidate() → computeScroll()

scrollTo 與 scrollBy 是 View 移動的兩個方法,它們更新 View 的新座標,接著呼叫 invalidate 或 postInvalidate 刷新畫面;滑動結束後再呼叫 computeScroll()。而 computeScroll() 在 View.java 裡只是一個空方法,內容要由我們自己填。

兩個靈魂拷問

問:如果在 computeScroll() 裡呼叫 scrollTo/scrollBy,會怎樣?
答:形成一個死循環,在同一個位置不斷刷新 View。只是因為系統的緩存與優化機制,肉眼看不出它在刷而已。

問:如果在 computeScroll() 裡呼叫 scrollTo/scrollBy,同時持續改變 Y 座標呢?
答:一樣是死循環刷新,但因為 Y 座標一直在變,View 就會依座標規律上下移動。只要這個變化是有節奏的、慢慢遞進的,就達成了我們要的效果——平滑移動。

結論:Scroller 是座標計算工具,不是動畫引擎

有種撥雲見日的感覺。與其說 Scroller 是「View 平滑移動的輔助類」,不如說它是一個「按時間產生座標的計算器」。Scroller 跟 View 的滑動本身其實沒有直接關係,它只負責算出動畫在某個時間點該落在哪個位置,形成一條座標路線;View 沿著這條路線反覆 invalidate,畫面上看起來就是平滑移動了。

startScroll():只是記下起點與終點

public void startScroll(int startX, int startY, int dx, int dy, int duration) {
    mMode = SCROLL_MODE;
    mFinished = false;
    mDuration = duration;
    mStartTime = AnimationUtils.currentAnimationTimeMillis();
    mStartX = startX;
    mStartY = startY;
    mFinalX = startX + dx;
    mFinalY = startY + dy;
    mDeltaX = dx;
    mDeltaY = dy;
    mDurationReciprocal = 1.0f / (float) mDuration;
}

簡單到令人難以置信:只是設定了動畫起始時間、起點座標、終點座標和時長倒數(純粹為了後續計算方便)。但動畫其實已經「開始」了,只是還沒畫到螢幕上。因為記住了起始時間,Scroender 就能依時間差算出目前應有的座標,View 拿這個座標去 invalidate 就動起來了。

影響座標計算的另一個關鍵是插值器。在 public Scroller(Context context, Interpolator interpolator) 這個建構子裡有相關說明,也可以自帶自訂的 Interpolator,這裡不展開。

computeScrollOffset():真正算座標的地方

public boolean computeScrollOffset() {
    if (mFinished) {
        return false;
    }
    int timePassed = (int)(AnimationUtils.currentAnimationTimeMillis() - mStartTime);
    if (timePassed < mDuration) {
        switch (mMode) {
        case SCROLL_MODE:
            float x = timePassed * mDurationReciprocal;
            if (mInterpolator == null)
                x = viscousFluid(x);
            else
                x = mInterpolator.getInterpolation(x);
            mCurrX = mStartX + Math.round(x * mDeltaX);
            mCurrY = mStartY + Math.round(x * mDeltaY);
            break;
        case FLING_MODE:
            final float t = (float) timePassed / mDuration;
            final int index = (int) (NB_SAMPLES * t);
            final float t_inf = (float) index / NB_SAMPLES;
            final float t_sup = (float) (index + 1) / NB_SAMPLES;
            final float d_inf = SPLINE[index];
            final float d_sup = SPLINE[index + 1];
            final float distanceCoef = d_inf + (t - t_inf) / (t_sup - t_inf) * (d_sup - d_inf);
            mCurrX = mStartX + Math.round(distanceCoef * (mFinalX - mStartX));
            mCurrX = Math.min(mCurrX, mMaxX);
            mCurrX = Math.max(mCurrX, mMinX);
            mCurrY = mStartY + Math.round(distanceCoef * (mFinalY - mStartY));
            mCurrY = Math.min(mCurrY, mMaxY);
            mCurrY = Math.max(mCurrY, mMinY);
            if (mCurrX == mFinalX && mCurrY == mFinalY) {
                mFinished = true;
            }
            break;
        }
    } else {
        mCurrX = mFinalX;
        mCurrY = mFinalY;
        mFinished = true;
    }
    return true;
}

重點在於:動畫還沒結束就算出目前座標,結束了就直接把座標拉到終點並標記完成。這裡有 SCROLL_MODE(手動拖曳的平滑模式)與 FLING_MODE(依手指滑動速率判斷的慣性模式)兩種分支。這個方法跑完後,通常根據回傳值決定要不要 invalidate,再由 View 把 scrollTo/scrollBy 移動到 Scroller 算好的新座標。

fling():慣性滑動

public void fling(int startX, int startY, int velocityX, int velocityY,
        int minX, int maxX, int minY, int maxY) {
    // Continue a scroll or fling in progress
    if (mFlywheel && !mFinished) {
        float oldVel = getCurrVelocity();
        float dx = (float) (mFinalX - mStartX);
        float dy = (float) (mFinalY - mStartY);
        float hyp = FloatMath.sqrt(dx * dx + dy * dy);
        float ndx = dx / hyp;
        float ndy = dy / hyp;
        float oldVelocityX = ndx * oldVel;
        float oldVelocityY = ndy * oldVel;
        if (Math.signum(velocityX) == Math.signum(oldVelocityX)
                && Math.signum(velocityY) == Math.signum(oldVelocityY)) {
            velocityX += oldVelocityX;
            velocityY += oldVelocityY;
        }
    }
    mMode = FLING_MODE;
    mFinished = false;
    float velocity = FloatMath.sqrt(velocityX * velocityX + velocityY * velocityY);
    mVelocity = velocity;
    final double l = Math.log(START_TENSION * velocity / ALPHA);
    mDuration = (int) (1000.0 * Math.exp(l / (DECELERATION_RATE - 1.0)));
    mStartTime = AnimationUtils.currentAnimationTimeMillis();
    mStartX = startX;
    mStartY = startY;
    float coeffX = velocity == 0 ? 1.0f : velocityX / velocity;
    float coeffY = velocity == 0 ? 1.0f : velocityY / velocity;
    int totalDistance = (int) (ALPHA * Math.exp(DECELERATION_RATE / (DECELERATION_RATE - 1.0) * l));
    mMinX = minX;
    mMaxX = maxX;
    mMinY = minY;
    mMaxY = maxY;
    mFinalX = startX + Math.round(totalDistance * coeffX);
    mFinalX = Math.min(mFinalX, mMaxX);
    mFinalX = Math.max(mFinalX, mMinX);
    mFinalY = startY + Math.round(totalDistance * coeffY);
    mFinalY = Math.min(mFinalY, mMaxY);
    mFinalY = Math.max(mFinalY, mMinY);
}

這個方法對應 GestureDetector.OnGestureListener 的 onFling 概念,依滑動速率決定後續行為,主要處理慣性的座標變化,實務上使用頻率不高。

abortAnimation():中止動畫

public void abortAnimation() {
    mCurrX = mFinalX;
    mCurrY = mFinalY;
    mFinished = true;
}

看原始碼就知道,停止動畫只是把座標拉到終點、設一個完成旗標,之後就不再計算了。

那段讓人糾結的 static 區塊

static {
    float x_min = 0.0f;
    for (int i = 0; i <= NB_SAMPLES; i++) {
        final float t = (float) i / NB_SAMPLES;
        float x_max = 1.0f;
        float x, tx, coef;
        while (true) {
            x = x_min + (x_max - x_min) / 2.0f;
            coef = 3.0f * x * (1.0f - x);
            tx = coef * ((1.0f - x) * START_TENSION + x * END_TENSION) + x * x * x;
            if (Math.abs(tx - t) < 1E-5) break;
            if (tx > t) x_max = x;
            else x_min = x;
        }
        final float d = coef + x * x * x;
        SPLINE[i] = d;
    }
    SPLINE[NB_SAMPLES] = 1.0f;
    // This controls the viscous fluid effect (how much of it)
    sViscousFluidScale = 8.0f;
    // must be set to 1.0 (used in viscousFluid())
    sViscousFluidNormalize = 1.0f;
    sViscousFluidNormalize = 1.0f / viscousFluid(1.0f);
}

這段程式讓我卡了很久。我的理解是:它把慣性模式的位移比例切成 NB_SAMPLES 份,用二分法反解到 0.00001 的精度,填進 SPLINE 表;慣性滑動時只要拿目前時間比例查表,就能得到對應的座標位置。

說到底,Android 的動畫本質上就是對座標的精確計算。這裡只是最基礎的平滑滑動,有能力的人完全可以照自己的需求寫一套座標計算類,做出想要的動感。

Scroller 的實際用法這裡不再贅述,推薦一篇寫得很清楚的範例文章:https://ipjmc.iteye.com/blog/1615828,裡頭有完整的 demo 可以參考,歡迎留言討論。

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