Android帧动画

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);           
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.在res/drawable目录下一个文件lottery_animlist.xml,内容如下: 2. 设置动画只...
    流沙3333阅读 429评论 0 0
  • 最近工作比较清闲,所以想系统的复习和学习下自己比较短缺的知识,所以。。。 程序运行效果图: Android动画主要...
    小沈新手阅读 529评论 0 1
  • FrameAnimation 如果有播放超多帧动画的需求,直接点击 FrameAnimation 在github查...
    yuashuai阅读 6,629评论 1 12
  • 帧动画就是图片的循环播放1 在drawable目录下新建一个根元素为animation-list的文件 2 在文件...
    shenlong77阅读 1,231评论 0 1
  • 关于帧动画网上有了许多,但是更适合自己的应该是自己读取一些博客后,自己的理解写出来, 帧动画就是将图片一张张播放,...
    沈凤德阅读 326评论 0 0