OPhone 2D UI 动画教程之一——Animation介绍

来源:互联网 发布:淘宝卖家怎样提前收款 编辑:程序博客网 时间:2024/04/24 07:43

在本系列教程中将介绍OPhone中提供的2D UI 动画(Animation),利用OPhone提供的动画功能可以很容易的创建各种UI动画效果,恰当的使用不同的动画组合可以使我们的程序更加招人喜爱。

OPhone 2D UI动画概述
在前面的《OPhone平台SurfaceView教程》中介绍了如何使用SurfaceView来创建一个现实GIF动画的自定义View,虽然OPhone不支持GIF动画显示但是OPhone却提供了其他动画效果。目前OPhone中提供了三种动画效果:逐帧动画(frame-by-frame animation),这种动画和GIF一样,一帧一帧的显示来组成动画效果;布局动画(layout animation),这种动画用来设置layout内的所有UI控件;控件动画(view animation),这种是应用到具体某个view上的动画。
 
在这三种动画实现中逐帧动画是最简单的,而控件动画是有点复杂的,要涉及到线性代数中的矩阵运算,下面就由易到难逐个介绍,先来看看逐帧动画如何实现。
 
逐帧动画
逐帧动画是通过OPhone中的android.graphics.drawable.AnimationDrawable类来实现的,在该类中保存了帧序列以及显示的时间,为了简化动画的创建OPhone提供了一种通过XML来创建逐帧动画的方式,这样把动画的创建和代码分来以后如果需要修改动画内容,只需要修改资源文件就可以了不用修改代码,简化开发维护工作。在res/drawable/文件夹下创建一个XML文件,下面是一个示例文件(res/drawable/qq_animation.xml):
view plaincopy to clipboardprint?
  1. <animation-list   
  2.     xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:oneshot="false">  
  4. <item android:drawable="@drawable/qq001" android:duration="80"/>  
  5. <item android:drawable="@drawable/qq002" android:duration="80"/>  
  6. <item android:drawable="@drawable/qq003" android:duration="80"/>  
  7. <item android:drawable="@drawable/qq004" android:duration="80"/>  
  8. <item android:drawable="@drawable/qq005" android:duration="80"/>  
  9. <item android:drawable="@drawable/qq006" android:duration="80"/>  
  10. <item android:drawable="@drawable/qq007" android:duration="80"/>  
  11. <item android:drawable="@drawable/qq008" android:duration="80"/>  
  12. </animation-list>  
 
 
在上面的定义中通过animation-list来指定这是个AnimationDrawable动画定义,里面的item来指定每帧图片和显示时间(单位为毫秒),帧显示的顺序就是item定义的顺序。如果android:oneshot设置为true表明该动画只播放一次,否则该动画会循环播放。这些设置也可以通过AnimationDrawable提供的函数来设置。动画中引用的文件为QQ表情文件,包含在示例项目代码中。
然后在layout中定义一个ImageView来显示上面定义的AnimationDrawable,layout代码如下(res/layout/main.xml):
view plaincopy to clipboardprint?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout   
  3. xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:orientation="vertical"   
  5.     android:layout_width="fill_parent"  
  6.     android:layout_height="fill_parent">  
  7.     <ImageView   
  8.        android:id="@+id/animation_view"  
  9.        android:layout_width="fill_parent"   
  10.        android:layout_height="wrap_content"  
  11.        android:src="@drawable/qq_animation" />  
  12.     <Button   
  13.        android:id="@+id/animation_btn"   
  14.        android:layout_width="fill_parent"  
  15.        android:layout_height="wrap_content"   
  16.        android:text="@string/start_animation" />  
  17.     <Button   
  18.        android:id="@+id/one_shot_btn"   
  19.        android:layout_width="fill_parent"  
  20.        android:layout_height="wrap_content"   
  21.        android:text="@string/play_once" />  
  22. </LinearLayout>  
注意这里的ImageView 通过android:src="@drawable/qq_animation"引用了前面定义的AnimationDrawable,下面是两个按钮用来控制播放动画和设置AnimationDrawable的oneshot属性。
下面就是控制动画播放的类代码(src/org/goodev/animation/AnimActivity.java):
 
view plaincopy to clipboardprint?
  1. public class AnimActivity extends Activity {  
  2.     /** Called when the activity is first created. */  
  3.     AnimationDrawable mAd;  
  4.     Button mPlayBtn;  
  5.     Button mOneShotBtn;  
  6.     boolean mIsOneShot;  
  7.    
  8.     @Override  
  9.     public void onCreate(Bundle savedInstanceState) {  
  10.        super.onCreate(savedInstanceState);  
  11.        setContentView(R.layout.main);  
  12.    
  13.        ImageView iv = (ImageView) findViewById(R.id.animation_view);  
  14.        mAd = (AnimationDrawable) iv.getDrawable();  
  15.    
  16.        mPlayBtn = (Button) findViewById(R.id.animation_btn);  
  17.        mPlayBtn.setOnClickListener(new OnClickListener() {  
  18.            @Override  
  19.            public void onClick(View view) {  
  20.               startAnimation();  
  21.            }  
  22.        });  
  23.    
  24.        mOneShotBtn = (Button) findViewById(R.id.one_shot_btn);  
  25.        mOneShotBtn.setOnClickListener(new OnClickListener() {  
  26.            @Override  
  27.            public void onClick(View view) {  
  28.               if (mIsOneShot) {  
  29.                   mOneShotBtn.setText("Play Once");  
  30.               } else {  
  31.                   mOneShotBtn.setText("Play Repeatly");  
  32.               }  
  33.               mAd.setOneShot(!mIsOneShot);  
  34.               mIsOneShot = !mIsOneShot;  
  35.            }  
  36.        });  
  37.    
  38.     }  
  39.    
  40.     /** 
  41.      * 通过AnimationDrawable的start函数播放动画, 
  42.      * stop函数停止动画播放, 
  43.      * isRunning来判断动画是否正在播放。 
  44.      */  
  45.     public void startAnimation() {  
  46.        if (mAd.isRunning()) {  
  47.            mAd.stop();  
  48.        } else {  
  49.            mAd.stop();  
  50.            mAd.start();  
  51.        }  
  52.     }  
  53. }  
  54.    
 
程序截图:
 
 
点击Start Animation按钮来播放动画,点击Play Once来交替设置是循环播放还是只播放一次。
 
关于AnimationDrawable的其他信息请参考AnimationDrawable文档,这里就不在赘述。
 
布局动画介绍
 
布局动画和逐帧动画是由本质的不同的,逐帧动画是一帧帧图片组成的,而布局动画是渐变动画,OPhone通过改变UI的属性(大小、位置、透明度等)来实现动画效果。
 
在OPhone显示系统中,每个view都对应一个矩阵来控制该view显示的位置,通过不同的方式来改变该控制矩阵就可以实现动画效果,例如旋转、移动、缩放等。
 
不同的矩阵变换有不同的类来实现,android.view.animation.Animation类代表所有动画变换的基类,目前在OPhone系统中有如下五个实现(都位于android.view.animation包中):
  • AlphaAnimation:实现alpha渐变,可以使界面逐渐消失或者逐渐显现
  • TranslateAnimation:实现位置移动渐变,需要指定移动的开始和结束坐标
  • ScaleAnimation: 实现缩放渐变,可以指定缩放的参考点
  • RotateAnimation:实现旋转渐变,可以指定旋转的参考点,默认值为(0,0)左上角。
  • AnimationSet: 代表上面的渐变组合
有一个和渐变动画效果关系比较密切的类android.view.animation.Interpolator,该类定义了渐变动画改变的速率,可以设置为加速变化、减速变化或者重复变化。关于Interpolator详细信息请参考文档介绍。另外在OPhone SDK中的android.jar文件中也有各种interpolator的定义,感兴趣的可以参考android.jar中的/res/anim目录中的文件。
 
动画的实现及应用
上面这些渐变方式也可以在XML文件中定义,这些文件位于res/anim目录下。根元素为set代表AnimationSet,里面可以有多个渐变定义,如下是alpha渐变的定义(res/anim/alpha_anim.xml):
view plaincopy to clipboardprint?
  1. <set xmlns:android="http://schemas.android.com/apk/res/android"  
  2. android:interpolator="@android:anim/decelerate_interpolator">  
  3. <alpha   
  4.     android:fromAlpha="0.0"   
  5.     android:toAlpha="1.0"   
  6.     android:duration="1000" />  
  7. </set>  
如果只定义一种渐变效果,则可以去除set元素,如下:
 
view plaincopy to clipboardprint?
  1. <alpha   
  2. xmlns:android="http://schemas.android.com/apk/res/android"  
  3. android:interpolator="@android:anim/accelerate_interpolator"  
  4. android:fromAlpha="0.0"   
  5. android:toAlpha="1.0"   
  6. android:duration="1000" />  
 
上面定义的alpha从0(透明)到1(不透明)渐变,渐变时间为1000毫秒。
 
view plaincopy to clipboardprint?
  1. <scale   
  2. xmlns:android="http://schemas.android.com/apk/res/android"  
  3. android:interpolator="@android:anim/accelerate_interpolator"  
  4. android:fromXScale="1"  
  5. android:toXScale="1"  
  6. android:fromYScale="0.1"  
  7. android:toYScale="1.0"  
  8. android:duration="500"  
  9. android:pivotX="50%"  
  10. android:pivotY="50%"  
  11. android:startOffset="100" />  
 
上面是一个缩放渐变的定义,from... 和 to... 分别定义缩放渐变的开始和结束的缩放倍数,上面定义X轴都为1不缩放,而Y轴从0.1到1逐渐放大(开始高度为正常大小的0.1然后逐渐放大到正常大小)。缩放持续的时间为500毫秒,缩放的中心点(通过pivotX,pivotY定义)在控件的中间位置。startOffset指定了在缩放开始前等待的时间。
view plaincopy to clipboardprint?
  1. <rotate   
  2. xmlns:android="http://schemas.android.com/apk/res/android"  
  3. android:interpolator="@android:anim/accelerate_interpolator"  
  4. android:fromDegrees="0.0"  
  5. android:toDegrees="360"  
  6. android:pivotX="50%"  
  7. android:pivotY="50%"  
  8. android:duration="500" />  
 
 
上面定义了旋转变换,从0度变化到360度(旋转一周),时间为500毫秒,变换的中心点位控件的中心位置。
view plaincopy to clipboardprint?
  1. <translate   
  2. xmlns:android="http://schemas.android.com/apk/res/android"  
  3. android:interpolator="@android:anim/accelerate_interpolator"  
  4. android:fromYDelta="-100%"   
  5. android:toYDelta="0"  
  6. android:duration="500" />  
 
 
上面定义了位置变换,实现一种下落的效果。
 
把上面不同的定义放到set中就可以实现不同的组合动画效果了,下面的示例实现了控件在下落的过程中逐渐显示的效果(res/anim/translate_alpha_anim.xml):
view plaincopy to clipboardprint?
  1. <set xmlns:android="http://schemas.android.com/apk/res/android"  
  2. android:interpolator="@android:anim/decelerate_interpolator">  
  3. <translate   
  4. android:fromYDelta="-100%"   
  5. android:toYDelta="0"  
  6. android:duration="500" />  
  7. <alpha   
  8. android:fromAlpha="0.0"   
  9. android:toAlpha="1.0"  
  10. android:duration="500" />  
  11. </set>  
 
 
要把上面定义的动画效果应用的layout中,就要使用另外一个类:android.view.animation.LayoutAnimationController。该类把指定的效果应用到layout中的每个控件上去,使用layoutAnimation元素在xml文件中定义
view plaincopy to clipboardprint?
  1. LayoutAnimationController,该文件同样位于res/anim/目录下,下面是一个示例(res/anim/layout_anim_ctrl.xml):  
  2. <layoutAnimation   
  3. xmlns:android="http://schemas.android.com/apk/res/android"  
  4. android:delay="30%"  
  5. android:animationOrder="reverse"  
  6. android:animation="@anim/translate_alpha_anim" />  
 
上面通过animation指定了使用哪个动画(通过修改该值可以测试不同的动画效果),animationOrder指定了通过逆序的方式应用动画(在垂直的LinearLayout中就是从下往上逐个控件应用),delay指定了layout中的每个控动画的延时时间为动画持续总时间的30%。
 
定义好LayoutAnimationController后就可以在Layout中使用了,这里使用一个ListView做演示,布局代码如下:
view plaincopy to clipboardprint?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout   
  3. xmlns:android="http://schemas.android.com/apk/res/android"  
  4. android:orientation="vertical"   
  5. android:layout_width="fill_parent"  
  6. android:layout_height="fill_parent">  
  7.     <ListView   
  8.     android:id="@+id/list"   
  9.     android:layout_width="fill_parent"  
  10.     android:layout_height="fill_parent"   
  11.       
  12.     android:persistentDrawingCache="animation|scrolling"  
  13.     android:layoutAnimation="@anim/layout_anim_ctrl" />  
  14. </LinearLayout>  
 
 
上面的代码中通过layoutAnimation指定了前面定义的LayoutAnimationController,为了使动画效果比较流畅这里还通过persistentDrawingCache设置了控件的绘制缓存策略,一共有4中策略:
PERSISTENT_NO_CACHE 说明不在内存中保存绘图缓存; 
PERSISTENT_ANIMATION_CACHE 说明只保存动画绘图缓存;
PERSISTENT_SCROLLING_CACHE 说明只保存滚动效果绘图缓存
PERSISTENT_ALL_CACHES 说明所有的绘图缓存都应该保存在内存中。
 
在Activity中并没有什么变化,代码如下(src/org/goodev/animation/ListActivity.java):
view plaincopy to clipboardprint?
  1. public class ListActivity extends Activity {  
  2.    
  3.     String[] mListItems =   
  4.     { "Item 1""Item 2""Item 3""Item 4""Item 5"};  
  5.    
  6.     @Override  
  7.     public void onCreate(Bundle savedInstanceState) {  
  8.        super.onCreate(savedInstanceState);  
  9.        setContentView(R.layout.list);  
  10.    
  11.        ArrayAdapter<String> listItemAdapter =   
  12.            new ArrayAdapter<String>(this,  
  13.               android.R.layout.simple_list_item_1, mListItems);  
  14.        ListView lv = (ListView) this.findViewById(R.id.list);  
  15.        lv.setAdapter(listItemAdapter);  
  16.     }  
  17. }  
 
 
控件动画介绍
其实控件动画也是布局动画的一种,可以看做是自定义的动画实现,布局动画在XML中定义OPhone已经实现的几个动画效果(AlphaAnimation、TranslateAnimation、ScaleAnimation、RotateAnimation)而控件动画就是在代码中继承android.view.animation.Animation类来实现自定义效果。
 
控件动画实现
通过重写Animation的 applyTransformation (float interpolatedTime, Transformation t)函数来实现自定义动画效果,另外一般也会实现 initialize (int width, int height, int parentWidth, int parentHeight)函数,这是一个回调函数告诉Animation目标View的大小参数,在这里可以初始化一些相关的参数,例如设置动画持续时间、设置Interpolator、设置动画的参考点等。
OPhone在绘制动画的过程中会反复的调用applyTransformation 函数,每次调用参数interpolatedTime值都会变化,该参数从0渐变为1,当该参数为1时表明动画结束。通过参数Transformation 来获取变换的矩阵(matrix),通过改变矩阵就可以实现各种复杂的效果。关于矩阵的详细信息可以参考android.graphics.Matrix的API文档(http://androidappdocs-staging.appspot.com/reference/android/graphics/Matrix.html )。
 
下面来看一个简单的实现:
   
view plaincopy to clipboardprint?
  1. class ViewAnimation extends Animation {  
  2.        public ViewAnimation() {  
  3.        }  
  4.    
  5.        @Override  
  6.         public void initialize(int width, int height, int parentWidth, int parentHeight) {  
  7.            super.initialize(width, height, parentWidth, parentHeight);  
  8.            setDuration(2500);  
  9.            setFillAfter(true);  
  10.            setInterpolator(new LinearInterpolator());  
  11.        }  
  12.    
  13.        @Override  
  14.         protected void applyTransformation(float interpolatedTime,  
  15.               Transformation t) {  
  16.            final Matrix matrix = t.getMatrix();  
  17.            matrix.setScale(interpolatedTime, interpolatedTime);  
  18.              
  19.        }  
  20.     }  
 
 
上面的代码很简单,在initialize函数中设置变换持续的时间2500毫秒,然后设置Interpolator为LinearInterpolator并设置FillAfter为true这样可以在动画结束的时候保持动画的完整性。在applyTransformation函数中通过MatrixsetScale函数来缩放,该函数的两个参数代表X、Y轴缩放因子,由于interpolatedTime是从0到1变化所在这里实现的效果就是控件从最小逐渐变化到最大。调用View的startAnimation函数(参数为Animation)就可以使用自定义的动画了。代码如下(src/org/goodev/animation/ViewAnimActivity.java):
 
view plaincopy to clipboardprint?
  1. public class ViewAnimActivity extends Activity {  
  2.    
  3.     Button mPlayBtn;  
  4.     ImageView mAnimImage;  
  5.    
  6.     @Override  
  7.     public void onCreate(Bundle savedInstanceState) {  
  8.        super.onCreate(savedInstanceState);  
  9.        setContentView(R.layout.view_anim_layout);  
  10.        mAnimImage = (ImageView) this.findViewById(R.id.anim_image);  
  11.    
  12.        mPlayBtn = (Button) findViewById(R.id.play_btn);  
  13.        mPlayBtn.setOnClickListener(new OnClickListener() {  
  14.    
  15.            @Override  
  16.            public void onClick(View view) {  
  17.               mAnimImage.startAnimation(new ViewAnimation());  
  18.            }  
  19.    
  20.        });  
  21.    
  22.     }  
  23. }  
 
 
布局代码如下(res/layout/view_anim_layout.xml):
view plaincopy to clipboardprint?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout   
  3. xmlns:android="http://schemas.android.com/apk/res/android"  
  4. android:orientation="vertical"  
  5. android:layout_width="fill_parent"  
  6. android:layout_height="fill_parent"  
  7. >   
  8. <Button  
  9. android:id="@+id/play_btn"  
  10. android:layout_width="fill_parent"  
  11. android:layout_height="wrap_content"  
  12. android:text="Start Animation"  
  13. />  
  14. <ImageView   
  15. android:id="@+id/anim_image"  
  16. android:persistentDrawingCache="animation|scrolling"  
  17. android:layout_width="fill_parent"   
  18. android:layout_height="wrap_content"   
  19. android:src="@drawable/ophone"  
  20. />  
  21. </LinearLayout>  
 
 
点击Start Animation按钮可以看到ImageView变化的效果,如下图所示:
图一:ImageView动画效果开始
图二:动画效果中间过程
图三:ImageView最终状态
 
从上图可以看到ImageView是从左上角出来的,这是由于没有指定矩阵的变换参考位置,默认位置为(0,0),如果要想让ImageView从中间出来,可以通过矩阵变换来把参考点移动到中间来,如下实现:
   
view plaincopy to clipboardprint?
  1. class ViewAnimation extends Animation {  
  2.        int mCenterX;//记录View的中间坐标  
  3.        int mCenterY;  
  4.        public ViewAnimation() {  
  5.        }  
  6.    
  7.        @Override  
  8.        public void initialize(int width, int height, int parentWidth, int parentHeight) {  
  9.            super.initialize(width, height, parentWidth, parentHeight);  
  10.            //初始化中间坐标值  
  11.            mCenterX = width/2;   
  12.            mCenterY = height/2;  
  13.            setDuration(2500);  
  14.            setFillAfter(true);  
  15.            setInterpolator(new LinearInterpolator());  
  16.        }  
  17.    
  18.        @Override  
  19.        protected void applyTransformation(float interpolatedTime,  
  20.               Transformation t) {  
  21.            final Matrix matrix = t.getMatrix();  
  22.            matrix.setScale(interpolatedTime, interpolatedTime);  
  23.            //通过坐标变换,把参考点(0,0)移动到View中间  
  24.            matrix.preTranslate(-mCenterX, -mCenterY);  
  25.            //动画完成后再移回来  
  26.            matrix.postTranslate(mCenterX, mCenterY);  
  27.        }  
  28.     }  
 
 
preTranslate函数是在缩放前移动而postTranslate是在缩放完成后移动。现在ImageView就是从中间出来的了。这样通过操作Matrix 可以实现各种复杂的变换。由于操作Matrix是实现动画变换的重点,这里简单介绍下Matrix的常用操作:
  • Reset():重置该矩阵
  • setScale():设置矩阵缩放
  • setTranslate():设置矩阵移动
  • setRotate():设置矩阵旋转
  • setSkew(): 使矩阵变形(扭曲)
 
矩阵也可以相乘,从线性代数中的矩阵运算中知道M1*M2 和M2*M1 是不一样的,所以在使用concat(m1,m2)函数的时候要注意顺序。
 
另外需要注意的是Matrix提供的API在OPhone1.0和OPhone1.5中是有变化的,请注意查看相关文档。
 
OPhone还提供了一个用来监听Animation事件的监听接口AnimationListener,如果你对Animatioin何时开始、何时结束、何时重复播放感兴趣则可以实现该接口。该接口提供了三个回调函数:onAnimationStart、onAnimationEnd、onAnimationRepeat。
 
使用Camera实现3D变换效果
最后来简单介绍下OPhone提供的android.graphics.Camera类,通过该类可以在2D条件下实现3D动画效果,该类可以看做一个视图显示的3D空间,然后可以在里面做各种操作。把上面的ViewAnimation修改为如下实现可以具体看看Camera的功能:
   
view plaincopy to clipboardprint?
  1.  class ViewAnimation extends Animation {  
  2.        int mCenterX;//记录View的中间坐标  
  3.        int mCenterY;  
  4.        Camera camera = new Camera();  
  5.        public ViewAnimation() {  
  6.        }  
  7.    
  8.        @Override  
  9.        public void initialize(int width, int height, int parentWidth,  
  10.               int parentHeight) {  
  11.            super.initialize(width, height, parentWidth, parentHeight);  
  12.            //初始化中间坐标值  
  13.            mCenterX = width/2;   
  14.            mCenterY = height/2;  
  15.            setDuration(2500);  
  16.            setFillAfter(true);  
  17.            setInterpolator(new LinearInterpolator());  
  18.        }  
  19.    
  20.        @Override  
  21.        protected void applyTransformation(float interpolatedTime,  
  22.               Transformation t) {  
  23. //         final Matrix matrix = t.getMatrix();  
  24. //         matrix.setScale(interpolatedTime, interpolatedTime);  
  25. //         //通过坐标变换,把参考点(0,0)移动到View中间  
  26. //         matrix.preTranslate(-mCenterX, -mCenterY);  
  27. //         //动画完成后再移回来  
  28. //         matrix.postTranslate(mCenterX, mCenterY);  
  29.            final Matrix matrix = t.getMatrix();  
  30.            camera.save();  
  31.            camera.translate(0.0f, 0.0f, (1300 - 1300.0f * interpolatedTime));  
  32.            camera.rotateY(360 * interpolatedTime);  
  33.            camera.getMatrix(matrix);  
  34.            matrix.preTranslate(-mCenterX, -mCenterY);  
  35.            matrix.postTranslate(mCenterX, mCenterY);  
  36.            camera.restore();  
  37.        }  
  38.     }  
 
camera.translate(0.0f, 0.0f, (1300 - 1300.0f * interpolatedTime))在第一次调用的时候interpolatedTime值为0,相当于把ImageView在Z轴后移1300像素,然后逐步的往前移动到0,同时camera.rotateY(360 * interpolatedTime)函数又把ImageView沿Y轴翻转360度,最终效果如下:
 
 
 
 
使用Camera后的动画效果
 
 
 
关于Camera的详细信息,请参考Camera文档这里不再赘述。
 
总结:
本教程介绍了OPhone中提供的2D animation的使用方式,在程序中合理的使用animation会给程序带来不少亮点,例如在程序首页使用一个优美的逐帧动画做背景这样会显得程序更加生动。

原创粉丝点击