帧动画的实现

2018-04-20  本文已影响0人  安多人

Android中帧动画,就是一帧一帧的播放图片,就像放电影一样。它的实现有两种方式,一种是通过java语言实现,另一种是通过xml实现。我们需要实现的功能是,响应一个按钮的点击事件,在imageview上来显示帧动画。
我们先用java来实现帧动画。在MainActivityxml文件中,设置一个按钮和一个imageview。在MainActivity中的OnCreate()函数中写一个方法用来初始化帧动画。

initAnimationFrame();
public void initAnimationFrame(){
//初始化控件
ImagiveView imagiveView = findViewById(R.id.imagiveView);
Button button = findViewById(R.id.button);
button.setOnClickListener(new OnClickListener{
onClick(View view){
//帧动画对象
AnimationDrawable animation = new AnimationDrable();
animation.addFrame(getResource().getDrawable(R.dawrable.one),1000);//加载个帧   参数1为drawable,参数2为持续时间
animation.addFrame(getResource().getDrawable(R.dawrable.two),1000);
animation.addFrame(getResource().getDrawable(R.dawrable.three),1000);
//将帧动画加载到imageview上
imageView.setBackground(animation);
//帧动画是否循环播放 为false时循环播放,为true时不循环播放
animation.oneShot(false);
//启动帧动画
animation.start();
}
});
};

通过xml文件实现
在drawable文件夹下新建一个文件名字为frame.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/one"
android:duration="100" />
<item
android:drawable="@drawable/two"
android:duration="100" />
<item
android:drawable="@drawable/three"
android:duration="100" />
<item
android:drawable="@drawable/four"
android:duration="100" />
<item
android:drawable="@drawable/five"
android:duration="100" />
<item
android:drawable="@drawable/six"
android:duration="100" />
<item
android:drawable="@drawable/seven"
android:duration="100" />
<item
android:drawable="@drawable/eight"
android:duration="100" />

</animation-list>
然后在MainActivity中的initAnimation函数中,
AnimationDrawable animatin =
(AnimationDrawable)getResource().getDrawable(R.drawable.frame));
imageView.setBackground(animation);
animation.start();

两者效果相同。
上一篇下一篇

猜你喜欢

热点阅读