Monday, March 15, 2010

Android: Tweened Animation

A tween animation is used to perform a series of simple transformations on a View object.

There are four possible transformations.
1. change position
2. change scale
3. change alpha value
4. rotate

There are two ways to define instructions in an animation.
1. define by XML
2. define by Android code

Here's a example demonstrating how to define animation by XML (res/anim/demo_one.xml).
This view will become transparent gradually as it move from center to left.

<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="500"/>
<translate android:fromXDelta="0" android:toXDelta="-50%p" android:duration="500" />
</set>

Specify which animation we would like to use by loadAnimation and apply it to an ImageView.

Animation anim = AnimationUtils.loadAnimation(this, R.anim.demo_one);
ImageView image = (ImageView) findViewById(R.id.android_icon);
image.startAnimation(anim);

Here are steps to define the animation as above example by Android code.
1. create a new class which extends AlphaAnimation
2. overwrite applyTransformation method (refer to Android example: Rotate3DAnimation for more information)

protected void applyTransformation(float interpolatedTime, Transformation t)
{
Matrix matrix = t.getMatrix();
Camera cam = new Camera();
cam.save();
cam.translate(shiftX*interpolatedTime, 0, 0);
cam.getMatrix(matrix);
cam.restore();
}


ref: Android 2D Graphics, Available Resource Types

No comments:

Post a Comment