Android 学习之逐帧动画(Frame)

来源:互联网 发布:网页游戏挂机软件 编辑:程序博客网 时间:2024/05/01 05:49

帧动画就是将一些列图片,依次播放。利用肉眼的“视觉暂留”的原理,给用户的感觉是动画的错觉,逐帧动画的原理和早期的电影原理是一样的。

a:需要定义逐帧动画,可以通过代码定义,也可以通过XML文件定义,一般XML文件定义比较直观

<?xml version="1.0" encoding="utf-8"?><animation-list xmlns:android="http://schemas.android.com/apk/res/android"     android:oneshot="false"> <!--false是循环播放  -->    <!-- drawables是每一张图片, duration是图片持续的时间 -->    <item android:drawable="@drawable/g1" android:duration="200" />    <item android:drawable="@drawable/g2" android:duration="200" />    <item android:drawable="@drawable/g3" android:duration="200" />    <item android:drawable="@drawable/g4" android:duration="200" />    <item android:drawable="@drawable/g5" android:duration="200" />    <item android:drawable="@drawable/g6" android:duration="200" />    <item android:drawable="@drawable/g7" android:duration="200" />    <item android:drawable="@drawable/g8" android:duration="200" />    <item android:drawable="@drawable/g9" android:duration="200" />    <item android:drawable="@drawable/g10" android:duration="200" />    <item android:drawable="@drawable/g11" android:duration="200" /></animation-list>

其中oneshot代表的是否循环播放,false是循环播放,true是只播放一次

b:将上述的XMLd定义的资源,设置为ImageView的背景

        //找到imageview        ImageView iv = (ImageView) findViewById(R.id.iv);        //将帧动画的资源文件设置为imageview的背景        iv.setBackgroundResource(R.drawable.frameanimation);

c:获得AnimationDrawable对象

        //获取AnimationDrawable对象        AnimationDrawable ad = (AnimationDrawable) iv.getBackground();

d:开始播放动画就ok

    //开始播放动画        ad.start();

Activity整个代码:

public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);            //找到imageview        ImageView iv = (ImageView) findViewById(R.id.iv);        //将帧动画的资源文件设置为imageview的背景        iv.setBackgroundResource(R.drawable.frameanimation);        //获取AnimationDrawable对象        AnimationDrawable ad = (AnimationDrawable) iv.getBackground();        //开始播放动画        ad.start();    }}

演示效果:


0 0