Rotate N angle an ImageView respecting the initial angle in Android

0

How to rotate an image taking into account the angle it is currently?

Example when pressing a button rotate an image 180º a 180º

That is to say

click 0º a 180º
click 180º a 360º
click botón 0º...
    
asked by Webserveis 24.04.2017 в 23:07
source

2 answers

0

My solution starts with defining two animations from 0 to 180 and from 180 to 360, depending on what is needed to start an animation or another.

Definition of animations in XML

rotate_0_to_180.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false" >

    <rotate
        android:duration="@android:integer/config_longAnimTime"
        android:interpolator="@android:anim/decelerate_interpolator"
        android:pivotX="50%"
        android:pivotY="50%"
        android:fromDegrees="0"
        android:toDegrees="180" />

</set>

rotate_180_to_360.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false" >

    <rotate
        android:duration="@android:integer/config_longAnimTime"
        android:interpolator="@android:anim/decelerate_interpolator"
        android:pivotX="50%"
        android:pivotY="50%"
        android:fromDegrees="180"
        android:toDegrees="360" />

</set>

By clicking

Animation rotation;

if (!sortASC){
    rotation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.rotate_0_to_180);
} else {
    rotation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.rotate_180_to_360);
}

rotation.setFillEnabled(true);
rotation.setFillAfter(true);

sortBtnIcon.startAnimation(rotation);

Edited

Method without creating animations in xml

private float mCurrRotation = 0.0f;

Function rotateViewFromToDegreeAnim

private float rotateViewFromToDegreeAnim(View v, float degreeStart, float degrees, long velocity) {

    RotateAnimation rotateAnim = new RotateAnimation(degreeStart, degreeStart + degrees,
            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
    degreeStart = (degreeStart + degrees) % 360;

    rotateAnim.setInterpolator(new LinearInterpolator());
    rotateAnim.setDuration(velocity);
    rotateAnim.setFillEnabled(true);
    rotateAnim.setFillAfter(true);
    v.startAnimation(rotateAnim);

    return degreeStart;
}

Its use is as follows rotateViewFromToDegreeAnim(image_view,grados_iniciales,grados_a_girar,velocdad) returns the total number of degrees that the image will remain after the rotation.

To turn 90º to 90º

mCurrRotation = rotateViewFromToDegreeAnim(sortBtnIcon,mCurrRotation,90,300L);

To turn from 180º to 180º

mCurrRotation = rotateViewFromToDegreeAnim(sortBtnIcon,mCurrRotation,180,300L);

    
answered by 24.04.2017 в 23:07
0

A long time ago work with rotate the image use canvas in android studio you can visit the project

link

    
answered by 25.04.2017 в 06:20