我想按Fragment上的按钮翻转图像。我创建了一个类,该类扩展了Animation类,以使翻转的动画效果如下所示。
import android.graphics.Camera;
import android.graphics.Matrix;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Transformation;
public class FlipAnimation extends Animation {
private int centerX;
private int centerY;
private Camera camera = new Camera();
@Override
public void initialize(int width, int height, int parentWidth, int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
centerX = width / 2;
centerY = width / 2;
setDuration(1000);
setInterpolator(new DecelerateInterpolator());
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
final Matrix matrix = t.getMatrix();
camera.save();
camera.rotateY(180 * interpolatedTime);
camera.getMatrix(matrix);
// Move to image center before rotation, and move back after rotation.
matrix.preTranslate(-centerX, -centerY);
matrix.postTranslate(centerX, centerY);
camera.restore();
}
}
当我按下按钮时,按如下所示调用动画
public void flipImage() {
FlipAnimation flipAnimation = new FlipAnimation();
flipAnimation.setFillAfter(true);
imageView.startAnimation(flipAnimation);
}
当我第一次按下按钮时,图像正确翻转(旋转180度),但是当我再次按下按钮时,图像没有翻转回原始状态。
当我再次按下按钮时,旋转从原始状态开始,但是我希望它从第一步的结果开始。
答案 0 :(得分:1)
在您的班级中定义一个reverse
成员。调用applyTransformation
时,只需将reverse
切换成相反的方向并施加180度的负旋转即可。
Here are some useful examples.
boolean reverse = false;
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
final Matrix matrix = t.getMatrix();
camera.save();
// Rotate forward or backward.
if (reverse) {
camera.rotateY(180 * (1.0f - interpolatedTime));
} else {
camera.rotateY(180 * interpolatedTime);
}
camera.getMatrix(matrix);
// Move to image center before rotation, and move back after rotation.
matrix.preTranslate(-centerX, -centerY);
matrix.postTranslate(centerX, centerY);
// Reverse animation.
reverse = !reverse;
camera.restore();
}