2015-02-08 48 views
2

我已經申請到ImageView無限翻譯動畫:如何在整個翻譯動畫中實現均勻的速度?

Animation animation = new TranslateAnimation(0, 0, -500, 500); 
animation.setDuration(4000); 
animation.setFillAfter(false); 
myimage.startAnimation(animation); 
animation.setRepeatCount(Animation.INFINITE); 

我所注意到的是,在翻譯過程較慢當圖像是附近的開始和結束點相比距離其近一半時(中點)。

我猜android上翻譯動畫的速度並不統一。

如何在整個過程中使速度保持一致?

回答

3

我做了一些源代碼潛水調查。首先,請注意如果一個線性內插器是用來提供interpolatedTime值的TranslateAnimationapplyTransformation方法,所得到的翻譯將具有恆定的速度(因爲偏移dxdyinterpolatedTime(線149-160線性函數) ):

@Override 
protected void applyTransformation(float interpolatedTime, Transformation t) { 
    float dx = mFromXDelta; 
    float dy = mFromYDelta; 
    if (mFromXDelta != mToXDelta) { 
     dx = mFromXDelta + ((mToXDelta - mFromXDelta) * interpolatedTime); 
    } 
    if (mFromYDelta != mToYDelta) { 
     dy = mFromYDelta + ((mToYDelta - mFromYDelta) * interpolatedTime); 
    } 
    t.getMatrix().setTranslate(dx, dy); 
} 

applyTransformation由基部Animation類的getTransformation方法調用(線869-870):

... 
final float interpolatedTime = mInterpolator.getInterpolation(normalizedTime); 
applyTransformation(interpolatedTime, outTransformation); 
... 

根據用於setInterpolator方法(線382-392)的文檔,mInterpolator應默認爲一個線性內插器:

/** 
* Sets the acceleration curve for this animation. Defaults to a linear 
* interpolation. 
* 
* @param i The interpolator which defines the acceleration curve 
* @attr ref android.R.styleable#Animation_interpolator 
*/ 
public void setInterpolator(Interpolator i) { 
    mInterpolator = i; 
} 

然而,這好像是錯誤的:在Animation類兩個構造調用ensureInterpolator方法(線803-811):

/** 
* Gurantees that this animation has an interpolator. Will use 
* a AccelerateDecelerateInterpolator is nothing else was specified. 
*/ 
protected void ensureInterpolator() { 
    if (mInterpolator == null) { 
     mInterpolator = new AccelerateDecelerateInterpolator(); 
    } 
} 

這表明默認內插器是一個AccelerateDecelerateInterpolator。這解釋了你在問題中描述的行爲。

要真正回答你的問題,那麼,這樣看來,你應該修改你的代碼如下:

Animation animation = new TranslateAnimation(0, 0, -500, 500); 
animation.setInterpolator(new LinearInterpolator()); 
animation.setDuration(4000); 
animation.setFillAfter(false); 
myimage.startAnimation(animation); 
animation.setRepeatCount(Animation.INFINITE); 
+1

非常感謝。它只是一個月,我一直在編碼android。我不知道速度的這種行爲。你的回答澄清了我的疑問,並且我得到了進一步研究的指針。 – 2015-02-08 13:14:07