Balasubramanian
Balasubramanian

Reputation: 5530

How to do reverse animation from the animated position in android?

I am trying to animate the image using scale and rotate properties. I am able to start the animation. But how to do the reverse one from the animated position instead of the actual position of the image.

AnimatorSet animation = new AnimatorSet();
private void rotateImage(boolean isReverse) {
        if(isReverse){
            animation.playTogether(
                    ObjectAnimator.ofFloat(fingerPrintImage, "rotation", 0, 60),
                    ObjectAnimator.ofFloat(fingerPrintImage, "scaleX", 1, 0.5f),
                    ObjectAnimator.ofFloat(fingerPrintImage, "scaleY", 1, 0.5f)
            );
        }
       else {
            animation.playTogether(
                    ObjectAnimator.ofFloat(fingerPrintImage, "rotation", 0, 60),
                    ObjectAnimator.ofFloat(fingerPrintImage, "scaleX", 1, 1.3f),
                    ObjectAnimator.ofFloat(fingerPrintImage, "scaleY", 1, 1.3f)
            );
        }
        animation.setDuration(5000);
        animation.start();
    }

rotateImage(true);

Upvotes: 2

Views: 1742

Answers (1)

A Honey Bustard
A Honey Bustard

Reputation: 3503

Usually reversing your 'from' and 'to' float parameters f.e. :

ObjectAnimator.ofFloat(fingerPrintImage, "scaleX", 1, 1.3f) // forward

ObjectAnimator.ofFloat(fingerPrintImage, "scaleX", 1.3f, 1) //backward

gives you an backward effect.

For animations like this, I strongly recommend ViewPropertyAnimator. It is super concise and has less code, no need for AnimationSets (which are often buggy), and you can chain different animations in one line :

private void rotateImage(boolean isReverse) {
    if(isReverse){
       fingerPrintImage.animate().rotationBy(-60).scaleXBy(0.3f).scaleYBy(0.3f).setDuration(5000);
    } else {
       fingerPrintImage.animate().rotationBy(60).scaleXBy(-0.3f).scaleYBy(-0.3f).setDuration(5000);
}

Maybe you have to tweak your values a bit, but this should be all you need.

Even shorter and more dynamic would be passing all float values through function parameters :

private void rotateImage(View view, float rotate, float scaleY, float scaleX, long duration) {
    view.animate().rotationBy(rotate).scaleXBy(scaleX).scaleYBy(scaleY).setDuration(duration);
}

which then can be called like :

rotateImage(fingerPrintImage, 60, 0.3f, 0,3f, 5000); // forward
rotateImage(fingerPrintImage, 60, -0.3f, -0.3f, 5000) //backwards

this minimizes code, gets rid of the isReverse boolean, and you are also able to reuse the method with different parameters for further animations.

Upvotes: 2

Related Questions