Android备忘录《帧动画》

帧动画

特点

  • 通过播放一组定义好的图片,像电影哪种方式,来实现的一种动画。
  • 三种动画中实现最简单的,由于是纯加载图片实现动画,所以会消耗更多内存,也更容易产生OOM,所以使用图片越小越好。
  • 通常用在一些简单的Loading图标,下拉上拉图标等。
  • 作用于View(Button,TextView...),但不能修改View的属性(背景,颜色,大小...)

实现方式

  • 通过XML文件来定义

res/anim的文件夹里创建动画效果.xml文件

xml代码

<?xml version="1.0" encoding="utf-8"?>
<animation-list
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="true"> // 设置是否只播放一次,默认为false
    // item = 动画图片资源;duration = 设置一帧持续时间(ms)
    <item android:drawable="@drawable/a0" android:duration="100"/>
    <item android:drawable="@drawable/a1" android:duration="100"/>
    <item android:drawable="@drawable/a2" android:duration="100"/>
    <item android:drawable="@drawable/a3" android:duration="100"/>
    <item android:drawable="@drawable/a4" android:duration="100"/>
    <item android:drawable="@drawable/a5" android:duration="100"/>
</animation-list>
复制代码

启动/停止

ImageView frameAnimationImage = (ImageView)findViewById(R.id.animation_frame_image);
frameAnimationImage.setImageResource(R.drawable.frame_animation_drawable);
AnimationDrawable animationDrawable = (AnimationDrawable) frameAnimationImage.getDrawable();
animationDrawable.start();

AnimationDrawable animationDrawable = (AnimationDrawable) frameAnimationImage.getDrawable();
animationDrawable.stop();
复制代码
  • 通过Java代码来实现
//Java代码实现帧动画
AnimationDrawable animation = new AnimationDrawable();
//第一个参数为动画图片资源,第二个参数为执行时间
animation.addFrame(ContextCompat.getDrawable(context,R.drawable.frame_animation_a), 200);
animation.addFrame(ContextCompat.getDrawable(context,R.drawable.frame_animation_b), 200);
animation.addFrame(ContextCompat.getDrawable(context,R.drawable.frame_animation_c), 200);
animation.setOneShot(false);

frameAnimationImage.setImageDrawable(animation);
animation.stop();
//特别注意:在动画start()之前要先stop(),不然在第一次动画之后会停在最后一帧,这样动画就只会触发一次
animation.start();
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值