Rotate an image in Android Studio

1

I want to rotate an image, but what I do not want is that when it rotates it moves away from its site. Rather, it rotates in its place without being moved. As a kind of roulette. How could I do it? Here is the code that I was testing but when executing it, it is detached from its place of origin. : (

RotateAnimation animation= new RotateAnimation(
           0,360,120,120);
            animation.setDuration(2000);
            animation.setRepeatCount(Animation.INFINITE);
            animation.setRepeatMode(Animation.REVERSE);
            imageView.startAnimation(animation);
    
asked by Santiago 05.05.2018 в 07:14
source

1 answer

0

To rotate a view with RotateAnimation , it is easier to use the constructor that receives 6 arguments , since we can indicate that the animation is about itself and give it a percentage, which will be programmatically given a value included between 0 and 1 of float type. The advantage of this constructor with respect to the one you are using, is that we do not have to give it an absolute value.

RotateAnimation animation = new RotateAnimation(
            0,
            360,
            RotateAnimation.RELATIVE_TO_SELF, 0.5f, //Como debe interpretarse pivotXValue
            RotateAnimation.RELATIVE_TO_SELF, 0.5f);

I leave you a simple example and its result ..

XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="238dp"
        android:layout_height="223dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/android" />
</android.support.constraint.ConstraintLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = (ImageView) findViewById(R.id.imageView);
        rotarImagen(imageView);

    }

    private void rotarImagen(View view){
        RotateAnimation animation = new RotateAnimation(0, 360,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f,
                RotateAnimation.RELATIVE_TO_SELF, 0.5f);

        animation.setDuration(2000);
        animation.setRepeatCount(Animation.INFINITE);
        animation.setRepeatMode(Animation.REVERSE);
        view.startAnimation(animation);
    }

}

Result:

    
answered by 05.05.2018 / 19:08
source