How to make a smooth image rotation in Android?

emmby picture emmby · Oct 28, 2009 · Viewed 240.6k times · Source

I'm using a RotateAnimation to rotate an image that I'm using as a custom cyclical spinner in Android. Here's my rotate_indefinitely.xml file, which I placed in res/anim/:

<?xml version="1.0" encoding="UTF-8"?>
<rotate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:toDegrees="360"
    android:pivotX="50%"
    android:pivotY="50%"
    android:repeatCount="infinite"
    android:duration="1200" />    

When I apply this to my ImageView using AndroidUtils.loadAnimation(), it works great!

spinner.startAnimation( 
    AnimationUtils.loadAnimation(activity, R.anim.rotate_indefinitely) );

The one problem is that the image rotation seems to pause at the top of every cycle.

In other words, the image rotates 360 degrees, pauses briefly, then rotates 360 degrees again, etc.

I suspect that the problem is that the animation is using a default interpolator like android:iterpolator="@android:anim/accelerate_interpolator" (AccelerateInterpolator), but I don't know how to tell it not to interpolate the animation.

How can I turn off interpolation (if that is indeed the problem) to make my animation cycle smoothly?

Answer

Bakhtiyor picture Bakhtiyor · Oct 28, 2009

You are right about AccelerateInterpolator; you should use LinearInterpolator instead.

You can use the built-in android.R.anim.linear_interpolator from your animation XML file with android:interpolator="@android:anim/linear_interpolator".

Or you can create your own XML interpolation file in your project, e.g. name it res/anim/linear_interpolator.xml:

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

And add to your animation XML:

android:interpolator="@anim/linear_interpolator"

Special Note: If your rotate animation is inside a set, setting the interpolator does not seem to work. Making the rotate the top element fixes it. (this will save your time.)