Android 逐帧动画

595 阅读1分钟

逐帧动画

帧动画也属于 View 动画,只是它的表现形式和其它四种不太一样。 帧动画是顺序播放一组预先定义好的图片,通过 AnimationDrawable 类来使用。 它比较容易引起 OOM,所以使用时应尽量避免使用过多尺寸较大的图片。

用来逐帧显示预先定义好的一组图片,类似于电影播放。对应于AnimationDrawable类。

FILE LOCATION:
    res/drawable/filename.xml
    The filename will be used as the resource ID.
COMPILED RESOURCE DATATYPE:
    Resource pointer to an AnimationDrawable.
RESOURCE REFERENCE:
    In Java: R.drawable.filename
    In XML: @[package:]drawable.filename
	
文件位置:
	res /drawable/ filename.xml
	文件名将用作资源ID。
编制资源数据类型:
	指向AnimationDrawable的资源指针。
资源引用:
	在Java: R.drawable.filename
	在XML: @包:drawable.filename

语法;

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot=["true" | "false"] >
	
	<--<animation-list>标签用来包含逐帧动画的每一帧-->
	<--android:oneshot 若为true,只播放一次。否则会循环播放。-->
	
    <item
        android:drawable="@[package:]drawable/drawable_resource_name"  // 当前帧对应的drawable资源
        android:duration="integer"                                     // 显示该帧的时间单位为毫秒。
		/>
		
</animation-list>

示例;

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="true">

    <item
        android:drawable="@drawable/img1"
        android:duration="1000" />
    <item
        android:drawable="@drawable/img2"
        android:duration="1000" />
    <item
        android:drawable="@drawable/img1"
        android:duration="1000" />
    <item
        android:drawable="@drawable/img2"
        android:duration="1000" />

</animation-list>
    // 动态创建
    AnimationDrawable animationDrawable = new AnimationDrawable();
    animationDrawable.addFrame(getResources().getDrawable(R.drawable.img1), 1000);
    animationDrawable.addFrame(getResources().getDrawable(R.drawable.img2), 1000);
    animationDrawable.addFrame(getResources().getDrawable(R.drawable.img1), 1000);
    animationDrawable.addFrame(getResources().getDrawable(R.drawable.img2), 1000);
    animationDrawable.setOneShot(true);
    iv.setImageDrawable(animationDrawable);
    animationDrawable.start();
	
    // 静态创建
    // iv.setImageResource(R.drawable.anim_frame);
    // AnimationDrawable animationDrawable = (AnimationDrawable) iv.getDrawable();
    // animationDrawable.start();

备注

欢迎关注微信公众号:非也缘也