Animation框架定义了透明度,旋转,缩放和位移几种常见的动画,而且控制的是整个View,实现原理是每次绘制视图时View所在的ViewGroup
中的childView函数获取该View的Animation的Transformation值,然后调用canvas.concat(transformToApply.getMatrix()),通过矩形矩阵
运算完成动画帧。如果动画没有完成,就继续调用invalidate()函数,启动下次绘制来驱动动画,从而完成整个动画的绘制。
动画主要分为视图动画和属性动画两种,视图动画使用比较简单,主要提供了AlphaAnimation,RotateAnimation,TransformAnimation
,ScaleAnimation四种动画方式,并且提供了AnimationSet动画集合,混合使用多种动画。相比属性动画,视图动画最大的缺陷就是不具备交互
性,当某一个元素发生视图动画之后,其相应事件的位置依然是在动画前达到位置,所以视图动画只能做普通的动画效果,避免交互的发生。视图动画
的使用不仅仅可以通过XML文件来描述一个动画过程,同样也可以使用代码来控制整个动画过程。
1.透明度动画:
// 透明度动画
AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
alphaAnimation.setDuration(1000);
view.startAnimation(alphaAnimation);
2.旋转动画
// 旋转动画
RotateAnimation rotateAnimation = new RotateAnimation(30, 180,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
rotateAnimation.setDuration(1000);
view.startAnimation(rotateAnimation);
3.位移动画
//位移动画
TranslateAnimation translateAnimation = new TranslateAnimation(10, 200, 10, 300);
translateAnimation.setDuration(1000);
view.startAnimation(translateAnimation);
4.缩放动画
// 缩放动画
ScaleAnimation scaleAnimation = new ScaleAnimation(0, 1, 0, 1,
ScaleAnimation.RELATIVE_TO_SELF, 0.5f,
ScaleAnimation.RELATIVE_TO_SELF, 0.5f);
scaleAnimation.setDuration(1000);
view.startAnimation(scaleAnimation);
5.集合动画
AnimationSet set = new AnimationSet(true);
set.setDuration(1000);
// 旋转动画
RotateAnimation rotateAnimation1 = new RotateAnimation(30, 180,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
rotateAnimation1.setDuration(1000);
set.addAnimation(rotateAnimation1);
//位移动画
TranslateAnimation translateAnimation1= new TranslateAnimation(10, 200, 10, 300);
translateAnimation1.setDuration(1000);
view.startAnimation(translateAnimation1);
set.addAnimation(translateAnimation1);
view.startAnimation(set);
6.动画的监听回调,可以获取到动画的开始,结束和重复事件,并且针对相应的事件作出不同的处理。
set.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});