【发布时间】:2015-02-04 09:31:27
【问题描述】:
我正在尝试制作一个节拍器,它的指针像倒立的钟摆一样移动。 我已经尝试过 RotationAnimation 的 android 来做到这一点,但它似乎在几次运行后变慢了。 我已经尝试过 LinearInterpolator 和自定义插值器(MetronomeInterpolator)。
以下代码取自Android How to rotate needle when speed changes?,感谢IHaN JiTHiN。
RotateAnimation needleDeflection = new RotateAnimation(
this.previousAngle, this.currentAngle, this.pivotX, this.pivotY) {
protected void applyTransformation(float interpolatedTime,
Transformation t) {
currentDegrees = previousAngle + (currentAngle - previousAngle)
* interpolatedTime;
currentValue = (((currentDegrees - minAngle) * (maxValue - minValue)) / (maxAngle - minAngle))
+ minValue;
if (NDL != null)
NDL.onDeflect(currentDegrees, currentValue);
super.applyTransformation(interpolatedTime, t);
}
};
needleDeflection.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation arg0) {
}
@Override
public void onAnimationRepeat(Animation arg0) {
}
@Override
public void onAnimationEnd(Animation arg0) {
previousAngle = currentAngle;
}
});
needleDeflection.setDuration(this.deflectTime);
needleDeflection.setInterpolator(new MetronomeInterpolator());
needleDeflection.setFillBefore(true);
needleDeflection.setFillAfter(false);
needleDeflection.setStartOffset(0);
needleDeflection.setRepeatMode(Animation.RESTART);
needleDeflection.setRepeatCount(Animation.INFINITE);
this.gaugeNeedle.startAnimation(needleDeflection);
this.gaugeNeedle.refreshDrawableState();
动画将无限次重启。
public class MetronomeInterpolator implements Interpolator {
private double p=0.5;
@Override
public float getInterpolation(float t) {
// a: amplitude, p: period/2
//https://stackoverflow.com/questions/1073606/is-there-a-one-line-function-that-generates-a-triangle-wave
double a=1;
return (float)((a/p) * (p - Math.abs(t % (2*p) - p)));
}
}
MetronomeInterpolator 正在形成三角波。公式取自Is there a one-line function that generates a triangle wave?,感谢Lightsider。
除了时间安排外,整个动画都完美无缺。动画第一次正确开始和结束。但是,重复几次后,动画似乎比应有的要慢。即背景播放的滴答声已被验证是准确的,但旋转动画在重复几次后滞后。
其中一个原因是某些代码在重复之前正在运行。您能否建议一种使用任何可在 android 中使用以制作准确钟摆的解决方案来制作动画的方法?非常感谢。
【问题讨论】:
标签: android animation rotation lag