Android开发之帧动画

286 阅读1分钟
Android动画主要分为3种

何为帧动画?

帧动画最简单,通过顺序播放一系列的图像产生动画,有点类似动画片

以会说话的Tom猫案例来讲解

1、首先准备好一组图片(网上找的现成的一组图片),然后定义一个AnimationDrawable,命名为ani.xml,按照图片顺序排好,如下:

<?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/background" android:duration="100"></item>
    <item android:drawable="@drawable/poke_belly_right_0001" android:duration="100"/>
    <item android:drawable="@drawable/poke_belly_right_0002" android:duration="100"/>
    <item android:drawable="@drawable/poke_belly_right_0003" android:duration="100"/>
    <item android:drawable="@drawable/poke_belly_right_0004" android:duration="100"/>
    <item android:drawable="@drawable/poke_belly_right_0005" android:duration="100"/>
    <item android:drawable="@drawable/poke_belly_right_0006" android:duration="100"/>
    <item android:drawable="@drawable/poke_belly_right_0007" android:duration="100"/>
    <item android:drawable="@drawable/poke_belly_right_0008" android:duration="100"/>
    <item android:drawable="@drawable/background" android:duration="100"></item>
</animation-list>

2、将上述的Drawable作为ImageView的背景

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/ani" />

</RelativeLayout>

3、通过AnimationDrawable 来播放动画,这里设置点击背景时触发动画,代码很简单,就没有加注释了

public class MainActivity extends Activity
{

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		ImageView imageView = (ImageView) findViewById(R.id.imageView1);

		final AnimationDrawable background = (AnimationDrawable) imageView
				.getBackground();
		imageView.setOnClickListener(new OnClickListener()
		{

			public void onClick(View v)
			{
				background.start();
			}
		});
	}

}

4、运行测试

帧动画.gif

5、注意点

帧动画虽然比较简单,但由于都是图片连续播放形成的,在图片比较多且较大的时候,容易引起OOM,所以需要谨慎选择。