Android中实现一个简单的逐帧动画(附代码下载)

时间:2023-03-09 07:02:35
Android中实现一个简单的逐帧动画(附代码下载)

场景

Android中的逐帧动画,就是由连续的一张张照片组成的动画。

效果

Android中实现一个简单的逐帧动画(附代码下载)

Android中实现一个简单的逐帧动画(附代码下载)

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi

关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

首先准备一组不同表情的照片,放在res/drawable下,然后在此目录下新建动画资源文件fairy.xml

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/img001" android:duration=""/>
<item android:drawable="@drawable/img002" android:duration=""/>
<item android:drawable="@drawable/img003" android:duration=""/>
<item android:drawable="@drawable/img004" android:duration=""/>
<item android:drawable="@drawable/img005" android:duration=""/>
<item android:drawable="@drawable/img006" android:duration=""/>
</animation-list>

这里是逐帧动画,所以节点是animation-list 。

然后来到布局文件,将布局设置为LinearLayout并添加id属性,并且设置背景为上面添加的动画资源文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@+id/linearLayout"
android:orientation="vertical"
android:background="@drawable/fairy"
android:layout_height="match_parent"
tools:context=".MainActivity"> </LinearLayout>

然后来到对应的Activity,创建标识变量Flag,然后获取AnimationDrawable对象,并且为布局管理器添加单击事件。从而控制动画的停止和播放。

package com.badao.animationtest;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout; public class MainActivity extends AppCompatActivity { private boolean flag = true; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout linearLayout= (LinearLayout) findViewById(R.id.linearLayout); //获取布局管理器
//获取AnimationDrawable对象
final AnimationDrawable anim= (AnimationDrawable) linearLayout.getBackground();
linearLayout.setOnClickListener(new View.OnClickListener() { //为布局管理器添加单击事件
@Override
public void onClick(View v) {
if(flag){
anim.start(); //开始播放动画
flag=false;
}else {
anim.stop(); //停止播放动画
flag=true;
}
}
});
}
}

代码下载

https://download.csdn.net/download/BADAO_LIUMANG_QIZHI/12097211