帧动画,顾名思义就是通过一帧一帧切换图片来实现动画效果。老式电影放映机就是这样的
优点:原理简单,实现也很简单
缺点:占资源,图片多了很容易OOM。
需要用到AnimationDrawable
方式一: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/dayu1" android:duration="50" />
<item android:drawable="@drawable/dayu2" android:duration="50" />
<item android:drawable="@drawable/dayu3" android:duration="50" />
<item android:drawable="@drawable/dayu4" android:duration="50" />
...
<item android:drawable="@drawable/dayu100" android:duration="50" />
</animation-list>
将资源设置为背景
<ImageView
android:id="@+id/img_show"
android:layout_width="800px"
android:layout_height="600px"
android:background="@drawable/yu_gif"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
通过View获取AnimationDrawable
对象
var annotation: AnimationDrawable = img_show.background as AnimationDrawable
方式二:代码生成对象
class DayuActivity : AppCompatActivity() {
val list = arrayOf(
R.drawable.dayu1,
R.drawable.dayu2,
R.drawable.dayu3,
R.drawable.dayu4,
...
R.drawable.dayu100
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_dayu)
//1 获取 AnimationDrawable对象
//a xml
//var annotation: AnimationDrawable = img_show.background as AnimationDrawable
//b 代码
var annotation: AnimationDrawable = AnimationDrawable()
for(id in list){
annotation.addFrame(resources.getDrawable(id),50)
}
img_show.background=annotation
//2 设置动画是否只执行一次
annotation.isOneShot = false
//3 开始动画
annotation.start()
}
}
![](https://img.haomeiwen.com/i4345135/caae9077a83bf9cc.gif)
网友评论