Android逐帧动画——让图片动起来
前言:逐帧动画要求开发者把动画过程的每张静态图片都收集起来,然后由android来控制依次显示这些静态图片,然后利用人眼视觉暂留的原理,给用户造成“动画”的错觉。通过逐帧动画我们就能让我们的图片“动起来”。
效果图:
定义逐帧动画只要在 < animation-list…/>元素中使用 < item…/>子元素定义动画的全部帧,并指定各帧的持续时间即可。
1. 第一步
在/res/drawable目录下,定义一个逐帧动画的资源文件fat_po.xml
android:oneshot="false">
animation-list>
该文件中将静态图片添加到逐帧动画,一张静态图片就对应一帧图像。
2. 第二步
在布局文件中添加两个按钮,一个用来控制逐帧动画的播放,一个用来控制逐帧动画的暂停。最后再添加一个ImageView来显示每一帧图像。
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.newdegree.mytest.FatPoActivity">
android:layout_height="wrap_content">
android:text="开始"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
android:text="暂停"
android:layout_weight="1"
android:layout_marginLeft="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
LinearLayout>
android:src="@drawable/fat_po"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
LinearLayout>
在 < ImageView …/> 标签中引入逐帧动画的资源文件,android:src=”@drawable/fat_po”。
2. 第三步
编写activity文件,在activity中控制逐帧动画的播放暂停。
public class FatPoActivity extends AppCompatActivity {
private Button btn_play,btn_pause;
private ImageView iv;
private AnimationDrawable anim;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fat_po);
btn_play = (Button) findViewById(R.id.play);
btn_pause = (Button) findViewById(R.id.pause);
iv = (ImageView) findViewById(R.id.anim);
iv.setImageResource(R.drawable.fat_po);
anim = (AnimationDrawable) iv.getDrawable();
btn_play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
anim.start();
}
});
btn_pause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
anim.stop();
}
});
}
}
总结:最后我们就完成了逐帧动画,一系列静态图片将会“动起来”了,但是还有一个问题,当我们要添加很多静态图片到一个逐帧资源文件中时,就会报java.lang.OutOfMemoryError异常。