Scroller类源码解析及其应用(一)
滑動是我們在自定義控件時候經(jīng)常遇見的難題,讓新手們倍感困惑,這篇文章主要介紹Scroller類的源碼,告訴打擊這個到底有什么用,怎么使用它來控制滑動。另外,我還會結(jié)合一個簡單的例子,來看一下這個類的應(yīng)用。
要說明Scroller類,我們往往要從另外兩個方法說起,一個是ScrollTo(),一個是ScrollBy()
這兩個方法我們可以在View的源碼看到,我們知道其實每個控件都有滾動條,只是有的我們將它隱藏,所以我們看不見
下面是ScrollTo方法
/*** Set the scrolled position of your view. This will cause a call to* {@link #onScrollChanged(int, int, int, int)} and the view will be* invalidated.* @param x the x position to scroll to* @param y the y position to scroll to*/public void scrollTo(int x, int y) {//滑動到的目標坐標if (mScrollX != x || mScrollY != y) {int oldX = mScrollX;//已經(jīng)滑動到的Xint oldY = mScrollY;//已經(jīng)滑動到的YmScrollX = x;mScrollY = y;onScrollChanged(mScrollX, mScrollY, oldX, oldY);//調(diào)用說明狀態(tài)改變if (!awakenScrollBars()) {invalidate();//通知視圖進行重繪}}}ScrollTo是一個public方法,說明我們可以在外部調(diào)用它,而正是我們調(diào)用了它,才能實現(xiàn)滑動,它的滑動效果是瞬間的,也就是說一步到位。傳進去的x,y是目的坐標,mScrollX,mScrollY是之前已經(jīng)滑動到位置,調(diào)用這個函數(shù)以后,我們可以看到mScrollX,mScrollY被我們重新賦值,接下來會調(diào)用invalidate()進行重繪
那么滑動的本質(zhì)是什么?根據(jù)動畫移動的基本原理,對于一個控件來說,它的大小是有限的(例如我們可以自己設(shè)定,或者說被父控件所束縛)。所以我們繪圖時會在這個有限的大小內(nèi)進行繪制,但是控件的Canvas本質(zhì)上是無限的,也就是一個控件的畫布大小是無限,控件的大小就像一個窗口,我們只是通過這個窗口去看這塊畫布。
所以滑動的本質(zhì)是,在窗口所見的畫布部分,我們畫些什么。
mScrollX,mScrollY起始是0,0,也就是說,窗口看見的,從畫布的左上角開始的,然后我們改變兩個值,例如100,100,窗口看見的,就是從100,100這個坐標開始繪制的東西(我們也可能沒有在這塊區(qū)域繪制東西,所以顯示空白,因為畫布是無限的)
說了這么多不知道大家有沒有聽懂,總之ScrollTo就是重新定義繪制起點坐標,從而實現(xiàn)滑動,由于繪制的一瞬間就開始的,所以ScrollTo造成的效果也是瞬間的
再來看看ScrollBy()方法
/*** Move the scrolled position of your view. This will cause a call to* {@link #onScrollChanged(int, int, int, int)} and the view will be* invalidated.* @param x the amount of pixels to scroll by horizontally* @param y the amount of pixels to scroll by vertically*/public void scrollBy(int x, int y) {scrollTo(mScrollX + x, mScrollY + y);}它里面調(diào)用了ScrollTo(),那樣我們就好理解了。傳入的參數(shù)是mScrollX+x,也就是說這次x是一個增量,所以scrollBy實現(xiàn)的效果就是,在原來的起始位置,偏移x距離,再重新繪制,這是ScrollTo()和ScrollBy()的重要區(qū)別。
OK,上面講了這么多,我們知道了用ScrollTo()就可以實現(xiàn)滑動了,但是我們需要的不是這樣的滑動,我們希望滑動是有過程的,要緩慢的滑,要有feeling。
做javascript的朋友可能會想到,我使用一個for循環(huán),然后每次調(diào)用ScrollBy()移動一定距離,每次移動后,讓進程沉睡一段時間,不久可以實現(xiàn)動畫的效果了嗎?
是的,這是一般的思維,開始這樣我們會面臨兩個問題,一個是讓主線程沉睡(這是萬萬不能),一個是假設(shè)我們要實現(xiàn)多樣的滑動算法(先快后慢,先慢后快等),怎么辦?
其實cpu每個一定時間就會從新繪制畫布(如果控件需要重新繪制的話),所以我們不必要讓主線程沉睡,至于后面一個問題確實值得考慮。
直接地說,解決辦法就是Scroller類,很多人看到這個類名,會不知道它跟滑動有什么關(guān)系。下面說一下,下面這段是Scroller的本質(zhì),只要聽懂了,這篇文章就算沒有白看了。
Scroller不能讓控件滑動,之所以不能,因為本質(zhì)上使控件滑動的是scrollTo()和scrollBy()方法
根據(jù)上面實現(xiàn)動畫的思想,我們有必要每次調(diào)用ScrollTo方法前,計算出的新的x,y值,而Scroller就是替我們計算這兩個值的
我們可以設(shè)定Scroller的內(nèi)部算法(用于實現(xiàn)滑動物理的效果,我們不需要了解具體算法內(nèi)容),然后調(diào)用Scroller的startScroll方法,這方法傳入起始坐標,目的坐標,和滑動完成所需的時間,一旦調(diào)用這個方法以后,我們就可以通過它的getCurrX(),getCurrY()方法獲得新的x,y坐標(這個兩個坐標,是通過內(nèi)部算法得來的)。
所以我們每次獲得新坐標,然后scrollTo就行了,就可以實現(xiàn)滑動了。那么我們每次什么時候滑動呢(按照什么頻率?難道真的寫for循環(huán)?),當然是cpu繪制的頻率最合理。
View里面有一個computeScroll()方法,在每次draw之前會調(diào)用,我們可以在調(diào)用這個方法時滑動(這個方法其實就是為我們滑動準備的啊!)
@Overridepublic void computeScroll() {}上面說的有點多,下面直接看scroller類源碼
首先是一些屬性,重要的我都有注釋,沒有注釋的,是默認算法需要的,我們不必理睬
/*** 模式,有SCROLL_MODE和FLING_MODE*/private int mMode;/*** 起始x方向偏移*/private int mStartX;/*** 起始y方向偏移*/private int mStartY;/*** 終點x方向偏移*/private int mFinalX;/*** 終點y方向偏移*/private int mFinalY;private int mMinX;private int mMaxX;private int mMinY;private int mMaxY;/*** 當前x方向偏移*/private int mCurrX;/*** 當前y方向偏移*/private int mCurrY;/*** 起始時間*/private long mStartTime;/*** 滾動持續(xù)時間*/private int mDuration;/*** 持續(xù)時間的倒數(shù)*/private float mDurationReciprocal;/*** x方向應(yīng)該滾動的距離,mDeltaX=mFinalX-mStartX*/private float mDeltaX;/*** y方向應(yīng)該滾動的距離,mDeltaY=mFinalY-mStartY*/private float mDeltaY;/*** 是否結(jié)束*/private boolean mFinished;/*** 插值器*/private Interpolator mInterpolator;/*** 調(diào)速輪*/private boolean mFlywheel;private float mVelocity;/*** 默認滑動時間*/private static final int DEFAULT_DURATION = 250;/*** 滑動模式*/private static final int SCROLL_MODE = 0;/*** 猛沖模式*/private static final int FLING_MODE = 1;private static float DECELERATION_RATE = (float) (Math.log(0.75) / Math.log(0.9));private static float ALPHA = 800; // pixels / secondsprivate static float START_TENSION = 0.4f; // Tension at start: (0.4 * total T, 1.0 * Distance)private static float END_TENSION = 1.0f - START_TENSION;private static final int NB_SAMPLES = 100;private static final float[] SPLINE = new float[NB_SAMPLES + 1];/*** 減速率*/private float mDeceleration;/*** pixels per inch*/private final float mPpi;然后來看構(gòu)造函數(shù)
/*** Create a Scroller with the specified interpolator. If the interpolator is* null, the default (viscous) interpolator will be used. Specify whether or* not to support progressive "flywheel" behavior in flinging.* 通過Ppi和滑動摩擦因素,計算減速率*/public Scroller(Context context, Interpolator interpolator, boolean flywheel) {mFinished = true;mInterpolator = interpolator;mPpi = context.getResources().getDisplayMetrics().density * 160.0f;mDeceleration = computeDeceleration(ViewConfiguration.getScrollFriction());mFlywheel = flywheel;}為控件創(chuàng)建scroller時,需要傳入context,另外interpolator是插值器,不同的插值器實現(xiàn)不同的動畫算法,如果我們不傳,則使用scroller內(nèi)部算法,接下面我就會看到另外flywheel是flywheel,有版本的限制,一般也不會用到,也是用于滑動動畫算法的實現(xiàn)
可以看到構(gòu)造函數(shù)里面,只是做了一些設(shè)定,mFinished表示滑動是否結(jié)束
再來看很重要的startScroll()方法
/*** Start scrolling by providing a starting point and the distance to travel.* The scroll will use the default value of 250 milliseconds for the* duration.* * @param startX Starting horizontal scroll offset in pixels. Positive* numbers will scroll the content to the left.* @param startY Starting vertical scroll offset in pixels. Positive numbers* will scroll the content up.* @param dx Horizontal distance to travel. Positive numbers will scroll the* content to the left.* @param dy Vertical distance to travel. Positive numbers will scroll the* content up.* 使用默認滑動時間完成滑動*/public void startScroll(int startX, int startY, int dx, int dy) {startScroll(startX, startY, dx, dy, DEFAULT_DURATION);}/*** Start scrolling by providing a starting point and the distance to travel.* * @param startX Starting horizontal scroll offset in pixels. Positive* numbers will scroll the content to the left.* 滑動起始X坐標* @param startY Starting vertical scroll offset in pixels. Positive numbers* will scroll the content up.* 滑動起始Y坐標* @param dx Horizontal distance to travel. Positive numbers will scroll the* content to the left.* X方向滑動距離* @param dy Vertical distance to travel. Positive numbers will scroll the* content up.* Y方向滑動距離* @param duration Duration of the scroll in milliseconds.* 完成滑動所需的時間 * 從起始點開始滑動一定距離*/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;}說它非常重要,但是內(nèi)部卻很簡單,就是定義滑動的起始坐標,目的坐標和滑動時間,所以說根本沒有實現(xiàn)滑動的效果
那么算法是在哪個方法里面調(diào)用的呢?
是computeScrollOffset()方法,這個方法返回false,說明滑動沒有結(jié)束,但是它更重要的作用是,利用內(nèi)部算法,起始坐標,目的坐標和滑動時間,從滑動開始到當前經(jīng)過的時間,計算出新的坐標
所以說,我們在獲取新的坐標前,一定要調(diào)用這個函數(shù),這個函數(shù)的功能非常重要,而且并不簡單!
從代碼可以看到,如果我們沒有設(shè)置插值器,就會調(diào)用內(nèi)部默認算法。 /*** 函數(shù)翻譯是粘性流體* 估計是一種算法*/static float viscousFluid(float x){x *= sViscousFluidScale;if (x < 1.0f) {x -= (1.0f - (float)Math.exp(-x));} else {float start = 0.36787944117f; // 1/e == exp(-1)x = 1.0f - (float)Math.exp(1.0f - x);x = start + x * (1.0f - start);}x *= sViscousFluidNormalize;return x;}接著是兩個重要的get方法 /*** Returns the current X offset in the scroll. * * @return The new X offset as an absolute distance from the origin.* 獲得當前X方向偏移*/public final int getCurrX() {return mCurrX;}/*** Returns the current Y offset in the scroll. * * @return The new Y offset as an absolute distance from the origin.* 獲得當前Y方向偏移*/public final int getCurrY() {return mCurrY;}
從scroller的整個源碼,我們都可以看到,根本沒有對控件進行重繪的操作。scroller只是一個利用滑動算法為控件提供新的繪制位置的工具,真正引起重繪的,是scrollTo方法,而這個方法需要我們主動調(diào)用(在computeScroll()里面)
另外scroller內(nèi)部還有許多的get方法,還有強制停止動畫效果的方法等,下面貼出scroller的完整代碼和注釋(我翻譯得很爛,大家海涵),大家可以看看一下
/** Copyright (C) 2006 The Android Open Source Project** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/package android.widget;import android.content.Context; import android.hardware.SensorManager; import android.os.Build; import android.util.FloatMath; import android.view.ViewConfiguration; import android.view.animation.AnimationUtils; import android.view.animation.Interpolator;/*** This class encapsulates scrolling. The duration of the scroll* can be passed in the constructor and specifies the maximum time that* the scrolling animation should take. Past this time, the scrolling is * automatically moved to its final stage and computeScrollOffset()* will always return false to indicate that scrolling is over.* 這個類封裝了滑動。滑動時間可以通過構(gòu)造函數(shù)傳入,并且制定滑動動畫完成所需的最大時間。* 這個時間以后,將會自動滑動到它的最終狀態(tài),并且computeScrollOffset()將返回false,表示滑動結(jié)束*/ public class Scroller {/*** 模式,有SCROLL_MODE和FLING_MODE*/private int mMode;/*** 起始x方向偏移*/private int mStartX;/*** 起始y方向偏移*/private int mStartY;/*** 終點x方向偏移*/private int mFinalX;/*** 終點y方向偏移*/private int mFinalY;private int mMinX;private int mMaxX;private int mMinY;private int mMaxY;/*** 當前x方向偏移*/private int mCurrX;/*** 當前y方向偏移*/private int mCurrY;/*** 起始時間*/private long mStartTime;/*** 滾動持續(xù)時間*/private int mDuration;/*** 持續(xù)時間的倒數(shù)*/private float mDurationReciprocal;/*** x方向應(yīng)該滾動的距離,mDeltaX=mFinalX-mStartX*/private float mDeltaX;/*** y方向應(yīng)該滾動的距離,mDeltaY=mFinalY-mStartY*/private float mDeltaY;/*** 是否結(jié)束*/private boolean mFinished;/*** 插值器*/private Interpolator mInterpolator;/*** 調(diào)速輪*/private boolean mFlywheel;private float mVelocity;/*** 默認滑動時間*/private static final int DEFAULT_DURATION = 250;/*** 滑動模式*/private static final int SCROLL_MODE = 0;/*** 猛沖模式*/private static final int FLING_MODE = 1;private static float DECELERATION_RATE = (float) (Math.log(0.75) / Math.log(0.9));private static float ALPHA = 800; // pixels / secondsprivate static float START_TENSION = 0.4f; // Tension at start: (0.4 * total T, 1.0 * Distance)private static float END_TENSION = 1.0f - START_TENSION;private static final int NB_SAMPLES = 100;private static final float[] SPLINE = new float[NB_SAMPLES + 1];/*** 減速率*/private float mDeceleration;/*** pixels per inch*/private final float mPpi;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);}private static float sViscousFluidScale;private static float sViscousFluidNormalize;/*** Create a Scroller with the default duration and interpolator.* 默認滑動時間和插值器*/public Scroller(Context context) {this(context, null);}/*** Create a Scroller with the specified interpolator. If the interpolator is* null, the default (viscous) interpolator will be used. "Flywheel" behavior will* be in effect for apps targeting Honeycomb or newer.* 調(diào)速輪只能在Honeycomb以上的版本有效*/public Scroller(Context context, Interpolator interpolator) {this(context, interpolator,context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB);}/*** Create a Scroller with the specified interpolator. If the interpolator is* null, the default (viscous) interpolator will be used. Specify whether or* not to support progressive "flywheel" behavior in flinging.* 通過Ppi和滑動摩擦因素,計算減速率*/public Scroller(Context context, Interpolator interpolator, boolean flywheel) {mFinished = true;mInterpolator = interpolator;mPpi = context.getResources().getDisplayMetrics().density * 160.0f;mDeceleration = computeDeceleration(ViewConfiguration.getScrollFriction());mFlywheel = flywheel;}/*** The amount of friction applied to flings. The default value* is {@link ViewConfiguration#getScrollFriction}.* * @param friction A scalar dimension-less value representing the coefficient of* friction.* 設(shè)置fling方法的摩擦因素大小 */public final void setFriction(float friction) {mDeceleration = computeDeceleration(friction);}/*** 計算減速率*/private float computeDeceleration(float friction) {return SensorManager.GRAVITY_EARTH // g (m/s^2)* 39.37f // inch/meter* mPpi // pixels per inch* friction;}/*** * Returns whether the scroller has finished scrolling.* * @return True if the scroller has finished scrolling, false otherwise.* 判斷滑動是否停止*/public final boolean isFinished() {return mFinished;}/*** Force the finished field to a particular value.* * @param finished The new finished value.* 強制滑動停止*/public final void forceFinished(boolean finished) {mFinished = finished;}/*** Returns how long the scroll event will take, in milliseconds.* * @return The duration of the scroll in milliseconds.* 獲得滑動時間*/public final int getDuration() {return mDuration;}/*** Returns the current X offset in the scroll. * * @return The new X offset as an absolute distance from the origin.* 獲得當前X方向偏移*/public final int getCurrX() {return mCurrX;}/*** Returns the current Y offset in the scroll. * * @return The new Y offset as an absolute distance from the origin.* 獲得當前Y方向偏移*/public final int getCurrY() {return mCurrY;}/*** Returns the current velocity.** @return The original velocity less the deceleration. Result may be* negative.*/public float getCurrVelocity() {return mVelocity - mDeceleration * timePassed() / 2000.0f;}/*** Returns the start X offset in the scroll. * * @return The start X offset as an absolute distance from the origin.*/public final int getStartX() {return mStartX;}/*** Returns the start Y offset in the scroll. * * @return The start Y offset as an absolute distance from the origin.*/public final int getStartY() {return mStartY;}/*** Returns where the scroll will end. Valid only for "fling" scrolls.* * @return The final X offset as an absolute distance from the origin.*/public final int getFinalX() {return mFinalX;}/*** Returns where the scroll will end. Valid only for "fling" scrolls.* * @return The final Y offset as an absolute distance from the origin.*/public final int getFinalY() {return mFinalY;}/*** Call this when you want to know the new location. If it returns true,* the animation is not yet finished. loc will be altered to provide the* new location.* 調(diào)用這個函數(shù)獲得新的位置坐標(滑動過程中)。如果它返回true,說明滑動沒有結(jié)束。* getCurX(),getCurY()方法就可以獲得計算后的值。*/ public boolean computeScrollOffset() {if (mFinished) {//是否結(jié)束return false;}int timePassed = (int)(AnimationUtils.currentAnimationTimeMillis() - mStartTime);//滑動開始,經(jīng)過了多長時間if (timePassed < mDuration) {//如果經(jīng)過的時間小于動畫完成所需時間switch (mMode) {case SCROLL_MODE:float x = timePassed * mDurationReciprocal;if (mInterpolator == null)//如果沒有設(shè)置插值器,利用默認算法x = viscousFluid(x); else//否則利用插值器定義的算法x = mInterpolator.getInterpolation(x);mCurrX = mStartX + Math.round(x * mDeltaX);//計算當前X坐標mCurrY = mStartY + Math.round(x * mDeltaY);//計算當前Y坐標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));// Pin to mMinX <= mCurrX <= mMaxXmCurrX = Math.min(mCurrX, mMaxX);mCurrX = Math.max(mCurrX, mMinX);mCurrY = mStartY + Math.round(distanceCoef * (mFinalY - mStartY));// Pin to mMinY <= mCurrY <= mMaxYmCurrY = 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;}/*** Start scrolling by providing a starting point and the distance to travel.* The scroll will use the default value of 250 milliseconds for the* duration.* * @param startX Starting horizontal scroll offset in pixels. Positive* numbers will scroll the content to the left.* @param startY Starting vertical scroll offset in pixels. Positive numbers* will scroll the content up.* @param dx Horizontal distance to travel. Positive numbers will scroll the* content to the left.* @param dy Vertical distance to travel. Positive numbers will scroll the* content up.* 使用默認滑動時間完成滑動*/public void startScroll(int startX, int startY, int dx, int dy) {startScroll(startX, startY, dx, dy, DEFAULT_DURATION);}/*** Start scrolling by providing a starting point and the distance to travel.* * @param startX Starting horizontal scroll offset in pixels. Positive* numbers will scroll the content to the left.* 滑動起始X坐標* @param startY Starting vertical scroll offset in pixels. Positive numbers* will scroll the content up.* 滑動起始Y坐標* @param dx Horizontal distance to travel. Positive numbers will scroll the* content to the left.* X方向滑動距離* @param dy Vertical distance to travel. Positive numbers will scroll the* content up.* Y方向滑動距離* @param duration Duration of the scroll in milliseconds.* 完成滑動所需的時間 * 從起始點開始滑動一定距離*/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;}/*** Start scrolling based on a fling gesture. The distance travelled will* depend on the initial velocity of the fling.* * @param startX Starting point of the scroll (X)* @param startY Starting point of the scroll (Y)* @param velocityX Initial velocity of the fling (X) measured in pixels per* second.* @param velocityY Initial velocity of the fling (Y) measured in pixels per* second* @param minX Minimum X value. The scroller will not scroll past this* point.* @param maxX Maximum X value. The scroller will not scroll past this* point.* @param minY Minimum Y value. The scroller will not scroll past this* point.* @param maxY Maximum Y value. The scroller will not scroll past this* point.* 開始基于滑動手勢的滑動。根據(jù)初始的滑動手勢速度,決定滑動的距離(滑動的距離,不能大于設(shè)定的最大值,不能小于設(shè)定的最小值) */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 progressif (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);// Pin to mMinX <= mFinalX <= mMaxXmFinalX = Math.min(mFinalX, mMaxX);mFinalX = Math.max(mFinalX, mMinX);mFinalY = startY + Math.round(totalDistance * coeffY);// Pin to mMinY <= mFinalY <= mMaxYmFinalY = Math.min(mFinalY, mMaxY);mFinalY = Math.max(mFinalY, mMinY);}/*** 函數(shù)翻譯是粘性流體* 估計是一種算法*/static float viscousFluid(float x){x *= sViscousFluidScale;if (x < 1.0f) {x -= (1.0f - (float)Math.exp(-x));} else {float start = 0.36787944117f; // 1/e == exp(-1)x = 1.0f - (float)Math.exp(1.0f - x);x = start + x * (1.0f - start);}x *= sViscousFluidNormalize;return x;}/*** Stops the animation. Contrary to {@link #forceFinished(boolean)},* aborting the animating cause the scroller to move to the final x and y* position** @see #forceFinished(boolean) * 強制停止滑動動畫,并且將目的坐標設(shè)置為當前坐標*/public void abortAnimation() {mCurrX = mFinalX;mCurrY = mFinalY;mFinished = true;}/*** Extend the scroll animation. This allows a running animation to scroll* further and longer, when used with {@link #setFinalX(int)} or {@link #setFinalY(int)}.** @param extend Additional time to scroll in milliseconds.* @see #setFinalX(int)* @see #setFinalY(int)* 延長滾動時間*/public void extendDuration(int extend) {int passed = timePassed();mDuration = passed + extend;mDurationReciprocal = 1.0f / mDuration;mFinished = false;}/*** Returns the time elapsed since the beginning of the scrolling.** @return The elapsed time in milliseconds.* 獲得已經(jīng)滾動的時間*/public int timePassed() {return (int)(AnimationUtils.currentAnimationTimeMillis() - mStartTime);}/*** Sets the final position (X) for this scroller.** @param newX The new X offset as an absolute distance from the origin.* @see #extendDuration(int)* @see #setFinalY(int)* 設(shè)置mScroller最終停留的水平位置,沒有動畫效果,直接跳到目標位置*/public void setFinalX(int newX) {mFinalX = newX;mDeltaX = mFinalX - mStartX;mFinished = false;}/*** Sets the final position (Y) for this scroller.** @param newY The new Y offset as an absolute distance from the origin.* @see #extendDuration(int)* @see #setFinalX(int)* 設(shè)置mScroller最終停留的豎直位置,沒有動畫效果,直接跳到目標位置*/public void setFinalY(int newY) {mFinalY = newY;mDeltaY = mFinalY - mStartY;mFinished = false;}/*** @hide*/public boolean isScrollingInDirection(float xvel, float yvel) {return !mFinished && Math.signum(xvel) == Math.signum(mFinalX - mStartX) &&Math.signum(yvel) == Math.signum(mFinalY - mStartY);} }更重要的是創(chuàng)建scroller來解決問題的這種思想,有點像記賬簿模式(記不清了,但肯定是設(shè)計模式的一種體現(xiàn))
轉(zhuǎn)載請注明出處http://blog.csdn.net/crazy__chen/article/details/45896961
對應(yīng)scroller的具體應(yīng)用,還有手勢滑動等內(nèi)容,大家可以參看下一篇文章
總結(jié)
以上是生活随笔為你收集整理的Scroller类源码解析及其应用(一)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一缕黑暗中的火光-----------U
- 下一篇: android沉浸式的实现