【发布时间】:2012-01-16 06:35:47
【问题描述】:
所以,我的问题有点类似于这两个问题:
Custom View onDraw is constantly called
android: onDraw is called constantly
我有一个扩展 ImageView 的自定义类,我将 RotateAnimation 应用到该类。动画使用输入的 x 和 y 坐标执行从上一个角度到下一个角度的旋转,因此用户可以根据需要将 ImageView 从 -360 度旋转到 360 度。当我将此代码用于 onDraw() 时,屏幕上的一切看起来都很完美(动画设置如下面的代码):
@Override
protected void onDraw(Canvas canvas) {
Log.d(TAG, "It is drawn again!");
this.setAnimation(anim);
super.onDraw(canvas);
}
问题在于,与提到的其他帖子中的方式相同,动画调用 onDraw 调用动画等等,可能是通过 RotateAnimation 类中的 invalidate()。这是否正确观察?输出非常完美,因为 ImageView 始终保持在当前计算的角度,但动画计算因此继续进行,消耗大量功率和容量。
为了解决这个问题,我尝试在计算动画参数的方法中移动 this.setAnimation(anim)(请忽略 isClockWise()、calculateAngleToMove() 和其他非 android 内容,它们按预期工作) :
private void turnWheel(){
float angle = 0;
if ( isClockWise() ){
angle = calculateAngleToMove();
anim = new RotateAnimation(current_angle, angle, center_x, center_y);
anim.setFillAfter(true);
anim.setFillEnabled(true);
current_angle += angle;
}
else{
angle = - calculateAngleToMove();
anim = new RotateAnimation(current_angle, angle, center_x, center_y);
anim.setFillAfter(true);
anim.setFillEnabled(true);
current_angle += angle;
}
if ( current_angle > 360 ){
current_angle = current_angle - 360;
}
if ( current_angle < -360 ){
current_angle = current_angle + 360;
}
this.setAnimation(anim);
this.invalidate(); //Calls onDraw()
}
这解决了 onDraw 不断被调用的问题,但它产生了另一个问题:当用户按下、按住和转动 ImageView 时,它会在零角度和当前角度之间来回切换。当用户随后放开 ImageView 时,它会回弹到零角度。希望始终以变量 current_angle 旋转 ImageView,即使在用户不提供输入时也是如此。
我尝试过不同版本的 anim.setFillAfter(true)、anim.setFillEnabled(true)、invalidate() 和 this.startAnimation(anim),但它们似乎对这个问题没有任何效果。
调用 this.setAnimation(anim) 的最佳位置在哪里?
【问题讨论】:
标签: android android-animation android-view