安卓动画片系列之三, 帧动画FrameAnimation
安卓动画系列之三, 帧动画FrameAnimation
帧动画, 顾名思义, 利用帧图来一帧一帧的播放,各个帧播放持续的时间的总和等于这个帧动画完整播放一次的周期时常.原理就像是剪辑电影一样,将一个个在连贯的画面连起来播放,就有动态自然连贯的效果.
并没什么艰深的知识点,上手很容易.所以依旧通过例子来上手.下面是效果图(图片来源于网络表情):
完整源码在文章底部会有下载链接.所以这里只讲一些关键的地方就够了:
在anim文件夹新建一个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/p1" android:duration="300" /> <item android:drawable="@drawable/p2" android:duration="300" /> <item android:drawable="@drawable/p3" android:duration="300" /> <item android:drawable="@drawable/p4" android:duration="300" /> </animation-list>
<animation-list> </animation-list> 是专门提供给帧动画使用的标签,里面<item>则对应每一帧, 通过drawable来使用你需要的图片, android:duration="300" 则是定义这一帧的时间长度为300ms, 这里共四帧,加起来这个动画完整播放一次的时间为1200ms.
<LinearLayout 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" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:gravity="center_horizontal" android:orientation="vertical" > <TextView android:text="@string/hello_world" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="18sp" android:textStyle="bold" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginTop="20dp" > <Button android:id="@+id/btn_start" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/start" /> <Button android:id="@+id/btn_stop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:text="@string/stop" /> </LinearLayout> <ImageView android:id="@+id/img_main" android:layout_width="200dp" android:layout_height="200dp" android:layout_marginTop="20dp" android:scaleType="fitXY" android:src="@anim/frame_animation" /> </LinearLayout>上面主要定义了2个按钮start 和 stop用于启动和停止动画.
在主类MainActivity中的主要代码:
//强制将ImageView的src内容转换为动画 final AnimationDrawable drawable = (AnimationDrawable)img.getDrawable(); btn_start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(drawable.isRunning()) drawable.stop(); //开始动画 drawable.start(); //停止动画的方法是drawable.stop(); //如果要人工停止动画可调用该stop()去中止动画的播放. } }); btn_stop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //停止动画 drawable.stop(); } });
源码地址