由于最近有个一翻转图片(view)的需求,写了个简单的翻转动画不多说上代码:
自定义的animation需要重写的方法有:
1. public void initialize(int width, int height, int parentWidth, int parentHeight) 初始化,按英文名字大家应该能猜到
2.protected void applyTransformation(float interpolatedTime, Transformation t) 实现自定义效果
public class FlipAnimation extends Animation {
private float fromDegree; // 旋转起始角度
private float toDegree; // 旋转终止角度
private float centerX = 0;
private float centerY = 0;
Camera camera = new Camera();
public FlipAnimation(float fromDegree , float toDegree){
this.fromDegree = fromDegree;
this.toDegree = toDegree;
}
@Override
public void initialize(int width, int height, int parentWidth, int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
centerX = width / 2;
centerY = height / 2;
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
//旋转角度, interpolatedTime为时间插值(范围为0-1)第一个参数就是通过getTransformation函数传递 反复调用此函数 不断刷新 view的信息达到动画效果
float degree = fromDegree + (toDegree - fromDegree) * interpolatedTime;
//此矩阵大家肯定不陌生, 三维矩阵 图像学中 通过此矩阵进行各种图像变换
Matrix matrix = t.getMatrix();
//跟canvas类似
camera.save();
// camera平移 达到缩放view效果, 注意camera默认位置(0,0,-8) location才能设置camera位置
//camera.translate(-0.0f, 0.0f,10.0f);
//做旋转变换
camera.rotateY(degree);
camera.getMatrix(matrix);
camera.restore();
//将(0,0)tranlate前、后中心点 具体参见http://www.360doc.com/content/14/0610/21/16623487_385518125.shtml
matrix.preTranslate(-centerX, -centerY);
matrix.postTranslate(centerX, centerY);
}
}
public class MainActivity extends ActionBarActivity {
private ImageView imageView1=null;
private Animation animation2;
private Animation animation1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView1= (ImageView) this.findViewById(R.id.imageView1);
imageView1.postDelayed(new Runnable() {
@Override
public void run() {
playFlipAnim(imageView1);
}
},1000);
}
private void playFlipAnim(final ImageView view){
FlipAnimation flipAinm = new FlipAnimation(0f, 90f);
flipAinm.setFillAfter(true);
flipAinm.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
view.setImageResource(R.drawable.image2);
//playFlip2Anim(view);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
flipAinm.setInterpolator(new AccelerateInterpolator());
flipAinm.setDuration(2000);
view.clearAnimation();
view.startAnimation(flipAinm);
}
private void playFlip2Anim(ImageView view){
FlipAnimation flipAinm = new FlipAnimation(270f, 360f);
flipAinm.setFillAfter(true);
flipAinm.setInterpolator(new AccelerateInterpolator());
flipAinm.setDuration(2000);
view.clearAnimation();
view.startAnimation(flipAinm);
}
}
总结由于camera 位置在(0,0,-8)位置 如view 的区域过大会造成一定的区域裁剪(view在翻转过程中显示不全),可以设置camera位置,不知大家有更好的建议没?