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

深入剖析 Android Scroller 的平滑滾動原理

編輯:關於 Android 程式設計

平滑滾動是什麼

簡單說,就是讓一個 View 在指定時間內從 A 點「滑」到 B 點,而不是瞬間跳過去。透過 Scroller,你可以做到等速、先加速後減速、先減速後加速等各種手感,很多炫麗的滑動動畫背後都是它。

用法三部曲

第一步,建立 Scroller 物件,通常放在 View 的建構子裡:

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

public ScrollViewGroup(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public ScrollViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    mScroller = new Scroller(context);
}

第二步,覆寫 computeScroll(),這段幾乎是固定寫法:

@Override
public void computeScroll() {
    super.computeScroll();
    if (mScroller.computeScrollOffset()) {
        scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
        postInvalidate();
    }
}

第三步,呼叫 startScroll(),前兩個參數是起點座標,後兩個是位移量:

mScroller.startScroll(int startX, int startY, int dx, int dy);
invalidate();

先搞懂 scrollTo 與 scrollBy

scrollTo 的源碼如下:

public void scrollTo(int x, int y) {
    if (mScrollX != x || mScrollY != y) {
        int oldX = mScrollX;
        int oldY = mScrollY;
        mScrollX = x;
        mScrollY = y;
        invalidateParentCaches();
        onScrollChanged(mScrollX, mScrollY, oldX, oldY);
        if (!awakenScrollBars()) {
            postInvalidateOnAnimation();
        }
    }
}

關鍵是最後那句 onScrollChanged(),它會讓 View 被重新繪製,於是畫面上就「動」了。而 scrollBy 其實只是 scrollTo 的包裝:

public void scrollBy(int x, int y) {
    scrollTo(mScrollX + x, mScrollY + y);
}

平滑從哪裡來

既然 scrollTo 是一次到位,那平滑效果的關鍵就是:把要走的距離切成很多小份,在一段時間內用 scrollTo 一點一點地移動。Scroller 正是靠這個原理運作——它負責算出「目前這個時間點應該在哪個位置」。

看構造器:

public Scroller(Context context, Interpolator interpolator, boolean flywheel) {
    mFinished = true;
    if (interpolator == null) {
        mInterpolator = new ViscousFluidInterpolator();
    } else {
        mInterpolator = interpolator;
    }
    mPpi = context.getResources().getDisplayMetrics().density * 160.0f;
    mDeceleration = computeDeceleration(ViewConfiguration.getScrollFriction());
    mFlywheel = flywheel;
    mPhysicalCoeff = computeDeceleration(0.84f); // look and feel tuning
}

主要工作就是決定插補器,沒特別指定的話預設使用 ViscousFluidInterpolator。

再看 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;
}

注意這裡根本沒有真的滾動,只是把一堆初始值設定好。真正讓它動起來的是下一句 invalidate():它使 View 重新繪製,而 View 在 draw 流程中會呼叫 computeScroll()。View 類別裡的 computeScroll 本身是空實作,等著我們去覆寫:

/**
 * Called by a parent to request that a child update its values for mScrollX
 * and mScrollY if necessary.
 */
public void computeScroll() {
}

核心的 computeScrollOffset:

public boolean computeScrollOffset() {
    if (mFinished) {
        return false;
    }
    int timePassed = (int) (AnimationUtils.currentAnimationTimeMillis() - mStartTime);
    if (timePassed < mDuration) {
        switch (mMode) {
            case SCROLL_MODE:
                final float x = mInterpolator.getInterpolation(timePassed * mDurationReciprocal);
                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);
                float distanceCoef = 1.f;
                float velocityCoef = 0.f;
                if (index < NB_SAMPLES) {
                    final float t_inf = (float) index / NB_SAMPLES;
                    final float t_sup = (float) (index + 1) / NB_SAMPLES;
                    final float d_inf = SPLINE_POSITION[index];
                    final float d_sup = SPLINE_POSITION[index + 1];
                    velocityCoef = (d_sup - d_inf) / (t_sup - t_inf);
                    distanceCoef = d_inf + (t - t_inf) * velocityCoef;
                }
                mCurrVelocity = velocityCoef * mDistance / mDuration * 1000.0f;
                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;
}

回傳值本身就是一個狀態旗標:true 代表還沒滑完,false 代表結束了。內部邏輯是先算已經過的時間 timePassed,若小於總時長就還沒結束,否則直接把 mFinished 設為 true。未結束時依 mode 分成兩支,但兩者做的事差不多:用時間比例配合插補器算出此刻應該停留的位置 mCurrX / mCurrY,也就是三部曲第二部裡 getCurrX() 與 getCurrY() 拿到的值。

把循環串起來

第二部曲呼叫 scrollTo 移動到該座標,接著再呼叫 postInvalidate() 讓 View 重繪,重繪又會觸發 computeScroll,於是形成一個自走的循環,直到抵達終點、computeScrollOffset 回傳 false 為止。

總結

Scroller 的原理其實相当直白:startScroll 準備參數 → invalidate 觸發繪製 → computeScroll 依時間算出目前位置 → scrollTo 移動 → 再 invalidate,如此反覆。理解這個迴圈之後,客製化各種滑動手感就只是換插補器與調整參數的事了。

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