美文网首页
Android帧动画

Android帧动画

作者: 疯子一般的勇士 | 来源:发表于2017-05-19 22:21 被阅读0次

1.xml文件
在res目录下建一个anim文件夹,在文件夹中创建一个“frame.xml”格式文件

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:Android="http://schemas.android.com/apk/res/android"
    android:oneshot="false">
    <item android:drawable="@drawable/a" android:duration="200" />
    <item android:drawable="@drawable/b" android:duration="200" />
    <item android:drawable="@drawable/c" android:duration="200" />
</animation-list>

duration属性是在此帧停留的毫秒值
oneshot属性表示是否只播放一次

用ImageView来播放帧动画

<ImageView
   android:id="@+id/_iv"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:background="@drawable/frame" />

代码中获取动画并开启

ImageView iv= (ImageView) findViewById(R.id.iv);
AnimationDrawable anim = (AnimationDrawable) iv.getBackground();
anim.start();
//anim.stop();

也可以在代码中给控件设置动画

iv.setBackgroundResource(R.anim.frame);

2.代码创建帧动画

ImageView iv= (ImageView) findViewById(R.id.iv);
AnimationDrawable anim= new AnimationDrawable();
//第一个参数是Drawable实例 第二个参数是毫秒值
anim.addFrame(getResources().getDrawable(R.drawable.img1), 200);
anim.addFrame(getResources().getDrawable(R.drawable.img2), 200);
anim.addFrame(getResources().getDrawable(R.drawable.img3), 200);
anim.addFrame(getResources().getDrawable(R.drawable.img4), 200);
 // 设置是否播放一次 true为播放一次
anim.setOneShot(false);
iv.setBackgroundDrawable(frameAnim);
anim.start();

以上是帧动画的两种实现方式
PS.长时间不用的东西真的容易忘啊

另外添加点东西,帧动画没有监听播放结束的回调接口,当有这方面需求时就需要自己想办法处理了

//获取动画运行时长,然后执行下步操作
AnimationDrawable an =(AnimationDrawable)imageView.getBackground();  
        animationDrawable.start();  
        int duration = 0;  
        for(int i=0;i<an .getNumberOfFrames();i++){  
            duration += an .getDuration(i);  
        }  
       Handler handler = new Handler();  
       handler.postDelayed(new Runnable() {  
           public void run() {  
              //此处进行下一步   
           }  
       }, duration);  

释放AnimationDrawable内存

        for (int i = 0; i < an .getNumberOfFrames(); i++) {
                Drawable frame = an .getFrame(i);
                if (frame instanceof BitmapDrawable) {
                        ((BitmapDrawable) frame).getBitmap().recycle();
                }
                frame.setCallback(null);
        }
        an .setCallback(null);           

相关文章

网友评论

      本文标题:Android帧动画

      本文链接:https://www.haomeiwen.com/subject/nzkuxxtx.html