帧动画学习

帧动画是使用多张连续图片逐帧播放出来
实现一个帧动画有两种方法,一种是通过布局文件静态实现,一种是通过代码的动态实现。帧动画主要用于实现下载进度动画等效果。

静态实现:
1.将连续的图片放到AS的mipmap-hdpi
2.在res的drawable下新建一个xml,根节点为animation-list,item为每一帧的节点
item节点的两个属性:duration设置一次的播放时间;drawable设置每一帧的图片资源
3.把这个资源文件设置成控件的背景
4.代码中通过空间的getBcakground()方法得到AnimationDrawable对象
5.通过AnimationDrawable的对象调用start();停止动画的方法stop();
6.通过AnimationDrawable的对象可以设置动画播放的属性,例如循环播放

<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:drawable="@mipmap/a2"
        android:duration="100" />
    <item
        android:drawable="@mipmap/a3"
        android:duration="100" />
    <item
        android:drawable="@mipmap/a4"
        android:duration="100" />
        ......
</animation-list>

3.在动图显示的页面加上ImageView

<ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        //这一句很重要
        android:background="@drawable/frame"
        />

4.代码部分

   /**
     * 先写一个startFrameAnim方法
     * 静态开始帧动画
     */
    private void startFrameAnim() {
        //把imageview控件的背景资源获取出来,转换成AnimationDrawable类型
        AnimationDrawable drawable = (AnimationDrawable) imageView.getBackground();
//        让动画资源开始的方法
        drawable.start();
    }

然后在onCreate里面调用

 imageView = (ImageView) findViewById(R.id.image);
   //        静态实现帧动画
               startFrameAnim();

动态实现:
1.创建一个AnimationDrawable的对象,使用new的方式
2.使用循环的方式把每一帧的图片资源添加到AnimationDrawable对象中
3.通过AnimationDrawable的对象调用start(),停止stop
4.通过AnimationDrawable的对象可以设置动画播放的属性,例如循环播放
注意:先给控件设置动画资源,然后再调用start()方法
1.在布局文件添加ImageView

        <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

2.添加实现动态帧动画的方法

   /**
     * 动态实现帧动画
     * 一般不常用
     */
    private void dongtaistartFramAnim() {
        AnimationDrawable animationDrawable = new AnimationDrawable();
//        通过resources方法把a2 - a20的图片加载到动画对象中
        for (int i = 2; i < 20; i++) {
//            1.图片名  2.图片所在的文件夹  3.当前的包名
            int id = getResources().getIdentifier("a" + i, "mipmap", getPackageName());
//            根据图片id把图片转化为Drawable对象
            Drawable frame = getResources().getDrawable(id);
//            把当前图片添加到AnimationDrawable对象中,并设置图片显示时间
            animationDrawable.addFrame(frame, 200);
        }
//        设置播放模式是否循环播放,false表示循环,true表示不循环
        animationDrawable.setOneShot(false);
//        设置本类将要显示的这个动画
        imageView.setBackgroundDrawable(animationDrawable);
//        启动动画
        animationDrawable.start();
    }

3.在OnCreate里面调用此方法即可

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值