Search code examples
androidandroid-animationandroid-imageviewandroid-image

Image starts rotating from starting position after one click


I have an image which is rotated by 36°. I used setFillAfter() and setFillEnabled(). It's saving the position but if I rotate it again it is starting from the original position. I want it to start from the position it was after rotation.

Animation animation = new Animation (0,36, Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
animation.setDuration(3000);
animation.setInterpolator(new LinearInterpolator());
animation.setFillAfter(true);

myImage.startAnimation(animation);

Solution

  • You just need to pass current angle of imageview in Animation Constructor instead of 0 everytime. Try below code:

            int rotationAngle=36;/*angle by which you want to rotate image*/
            int mCurrRotation = 0;  /*current angle of image*/
    
            buttonRotate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                float fromRotation = mCurrRotation;
                float toRotation = mCurrRotation += rotationAngle;
    
                Animation animation = new RotateAnimation(
                        fromRotation,
                        toRotation,
                        Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
    
    
                animation.setDuration(3000);
                animation.setFillAfter(true);
                myImage.startAnimation(animation);
            }
        });