Android提供Animation作为补间动画抽象基类,而且为该抽象基类提供了
AlphaAnimation,RotateAnimation,ScaleAnimation,TranslateAnimation四个类
但是在实际项目中,这些很可能不够用,可能需要一些更复杂的动画,比如说立体空间的旋转动画
基于特殊的要求,我们就需要继承Animation,重写applyTransformation(float interpolatedTime,Transformation)方法
interpolatedTime:代表了动画的时间进行比
Tansformation:该参数代表了初间动画在不同时刻对图形或组件的变形程度,其中封装了一个Matrix对象
为了控制图片或View进行三维的变换,还需要借助Android提供的Camera.手机的三维坐标系统有x,y,z三个轴
Camera对象提供了rotateX(float deg),rotateY(float deg),rotateZ(float deg)来沿着三个轴旋转
下面是一个例子,applyTransformation方法是重点
选定义一个自定义的动画类
package WangLi.Graphics.ListViewTween;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.Transformation;
public class MyAnimation extends Animation
{
private int centerX;
private int centerY;
//定义动画的持续事件
private int duration;
private Camera camera = new Camera();
public MyAnimation(int centerX, int centerY , int duration)
{
this.centerX = centerX;
this.centerY = centerY;
this.duration = duration;
}
@Override
public void initialize(int width, int height, int parentWidth,
int parentHeight)
{
super.initialize(width, height, parentWidth, parentHeight);
//设置动画的持续时间
setDuration(duration);
//设置动画结束后效果保留
setFillAfter(true);
setInterpolator(new LinearInterpolator());
}
/*
* 该方法的interpolatedTime代表了抽象的动画持续时间,不管动画实际持续时间多长,
* interpolatedTime参数总是从0(动画开始时)~1(动画结束时)
* Transformation参数代表了对目标组件所做的变.
*/
@Override
protected void applyTransformation(float interpolatedTime, Transformation t)
{
camera.save();
//根据interpolatedTime时间来控制X、Y、Z上的偏移
camera.translate(100.0f - 100.0f * interpolatedTime ,
150.0f * interpolatedTime - 150 ,
80.0f - 80.0f * interpolatedTime);
// 设置根据interpolatedTime时间在Y柚上旋转不同角度。
camera.rotateY(360 * (interpolatedTime));
// 设置根据interpolatedTime时间在X柚上旋转不同角度
camera.rotateX((360 * interpolatedTime));
//获取Transformation参数的Matrix对象
Matrix matrix = t.getMatrix();
camera.getMatrix(matrix);
matrix.preTranslate(-centerX, -centerY);
matrix.postTranslate(centerX, centerY);
camera.restore();
}
}
主界面
package WangLi.Graphics.ListViewTween;
import android.app.Activity;
import android.os.Bundle;
import android.view.Display;
import android.view.WindowManager;
import android.widget.ListView;
public class ListViewTween extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//获取ListView组件
ListView list = (ListView)findViewById(R.id.list);
WindowManager windowManager = (WindowManager)
getSystemService(WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
//获取屏幕的宽和高
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
//设置对ListView组件应用动画
list.setAnimation(new MyAnimation(screenWidth / 2
, screenHeight / 2 , 3500));
}
}