Pregunta

He creado un diseño con una vista de imagen y una vista web. La vista web se fija para tener una visibilidad predeterminada de ida. Cuando los fuegos de actividad hasta que muestra la vista de la imagen primero y cuando la vista web ha terminado de cargar su URL, que marca a sí mismo como visible y el imageview está marcado como oculto.

Cuando se muestra el imageview, me gustaría que gire varias veces sólo por un dinamismo añadido.

que nunca he hecho antes animaciones en Android y todos los mensajes que encontré cuando pregunté internet no era servicial; por lo tanto, he vuelto a SO en busca de ayuda.

Así que si comienzo con esto ...

    final ImageView splash = (ImageView)findViewById(R.id.splash);

¿Cómo se crea una animación de rotación repetida y aplicarlo a la ImageView?

Gracias de nuevo!

¿Fue útil?

Solución

Utilice un RotateAnimation , el ajuste del punto de pivote a la el centro de la imagen.

RotateAnimation anim = new RotateAnimation(0f, 350f, 15f, 15f);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(700);

// Start animating the image
final ImageView splash = (ImageView) findViewById(R.id.splash);
splash.startAnimation(anim);

// Later.. stop the animation
splash.setAnimation(null);

Otros consejos

Cómo rotar una imagen alrededor de su centro:

ImageView view = ... //Initialize ImageView via FindViewById or programatically

RotateAnimation anim = new RotateAnimation(0.0f, 360.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

//Setup anim with desired properties
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE); //Repeat animation indefinitely
anim.setDuration(700); //Put desired duration per anim cycle here, in milliseconds

//Start animation
view.startAnimation(anim); 
//Later on, use view.setAnimation(null) to stop it.

Esto hará que la imagen para girar alrededor de su centro (0,5 o 50% de su anchura / altura). Estoy publicar esto para futuros lectores que llegar desde Google, como yo, y que desean girar la imagen alrededor de su centro, sin definir dicho centro en píxeles absolutos.

También puede simplemente utilizar la función de animación Girar. Que se ejecuta una animación específica, para una cantidad predeterminada de tiempo, en una ImageView.

Animation rotate = AnimationUtils.loadAnimation([context], R.anim.rotate_picture);
splash.startAnimation(rotate);

A continuación, crear un archivo XML la animación en sus res / anim llama rotate_picture con el contenido:

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

    <rotate 
    android:fromDegrees="0"
    android:toDegrees="360"
    android:duration="5000"
    android:pivotX="50%"
    android:pivotY="50%">
</rotate>
</set>

Ahora, lamentablemente, esto sólo se ejecutará una vez. Usted necesitará un bucle en algún lugar para que se repita la animación mientras se está a la espera. Experimenté un poco y tengo mi programa ha quedado atascado en bucles infinitos, así que no estoy seguro de la mejor manera a eso. EDIT:! La respuesta de Christopher proporciona la información sobre cómo hacerlo correctamente bucle, por lo que la eliminación de mi mala sugerencia acerca de hilos separados

Una forma - que dividir la imagen en N girándolo un poco cada vez. Yo diría que 5 es suficiente. a continuación, crear algo como esto en dibujable

<animation-list   android:id="@+id/handimation" android:oneshot="false" 
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/progress1" android:duration="150" />
    <item android:drawable="@drawable/progress2" android:duration="150" />
    <item android:drawable="@drawable/progress3" android:duration="150" />
 </animation-list> 

inicio de código

progress.setVisibility(View.VISIBLE);
AnimationDrawable frameAnimation = (AnimationDrawable)progress.getDrawable();
frameAnimation.setCallback(progress);
frameAnimation.setVisible(true, true);

parada de código

AnimationDrawable frameAnimation = (AnimationDrawable)progress.getDrawable();
frameAnimation.stop();
frameAnimation.setCallback(null);
frameAnimation = null;
progress.setVisibility(View.GONE);

aquí

imgDics = (ImageView) v.findViewById(R.id.img_player_tab2_dics);
    imgDics.setOnClickListener(onPlayer2Click);
    anim = new RotateAnimation(0f, 360f,
            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                            0.5f);
    anim.setInterpolator(new LinearInterpolator());
    anim.setRepeatCount(Animation.INFINITE);
    anim.setDuration(4000);

    // Start animating the image
    imgDics.startAnimation(anim);

En el interior del elemento de poner:

android:repeatCount="infinite"

He descubierto, que si se utiliza el .getWidth / 2 etc ... que no va a funcionar que necesita para obtener el número de píxeles de la imagen es y se divide por 2 a sí mismo y luego simplemente escribe en el número de los últimos 2 argumentos.

así que decir que su imagen era una de píxeles de 120 por 120 píxeles cuadrados, ur x e y sería igual a 60 píxeles. por lo que en su código, lo haría derecha:

RotateAnimation anim = new RotateAnimation(0f, 350f, 60f, 60f);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(700);

y ahora su imagen girará alrededor de su centro.

código verificado:

imageView.setImageResource(R.drawable.ic_arrow_up);

boolean up = true;

if (!up) { 
    up = true; 
    imageView.startAnimation(animate(up)); 
} else { 
    up = false; 
    imageView.startAnimation(animate(up)); 
}

private Animation animate(boolean up) {
    Animation anim = AnimationUtils.loadAnimation(this, up ? R.anim.rotate_up : R.anim.rotate_down);
    anim.setInterpolator(new LinearInterpolator()); // for smooth animation
    return anim;
}

estirable / ic_arrow_up.xml

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#3d3d3d"
        android:pathData="M7.41,15.41L12,10.83l4.59,4.58L18,14l-6,-6 -6,6z"/>
</vector>

anim / rotate_up.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true"
    android:fillEnabled="true">
    <rotate
        android:duration="200"
        android:fromDegrees="-180"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toDegrees="0" />
</set>

anim / rotate_down.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true"
    android:fillEnabled="true">
    <rotate
        android:duration="200"
        android:fromDegrees="0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:toDegrees="180" />
</set>

No sale la imagen del código no duros. Sólo tiene que utilizar:

RotateAnimation anim = new RotateAnimation( fromAngle, toAngle, imageView.getDrawable().getBounds().width()/2, imageView.getDrawable().getBounds().height()/2);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top