点击这里可以查看我所有关于图形图像处理的文章
本篇文章是继续上一篇【Android】图形图像处理之“逐帧动画”(xml) 写的在java文件中进行处理的java版图形图像处理之“逐帧动画”。动画素材可以在【Android】图形图像处理之“逐帧动画”(xml)中获取。
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始"/>
<Button
android:id="@+id/stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="结束"/>
</LinearLayout>
<ImageView
android:id="@+id/animImg"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"/>
</LinearLayout>
和【Android】图形图像处理之“逐帧动画”(xml)的区别在哪呢?主要是在ImageView中,原先用来设定动画资源当成背景的 android:src=”@drawable/fly” 去掉了。
MainActivity.java
package com.file.file;
import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button start= (Button)findViewById(R.id.start);
final Button stop = (Button)findViewById(R.id.stop);
final ImageView animImg = (ImageView)findViewById(R.id.animImg);
final AnimationDrawable anim = new AnimationDrawable();
anim.addFrame(getResources().getDrawable(R.drawable.horse1),50);
anim.addFrame(getResources().getDrawable(R.drawable.horse2),50);
anim.addFrame(getResources().getDrawable(R.drawable.horse3),50);
anim.addFrame(getResources().getDrawable(R.drawable.horse4),50);
anim.addFrame(getResources().getDrawable(R.drawable.horse5),50);
anim.addFrame(getResources().getDrawable(R.drawable.horse6),50);
anim.addFrame(getResources().getDrawable(R.drawable.horse7),50);
anim.addFrame(getResources().getDrawable(R.drawable.horse8),50);
anim .setOneShot(false);
animImg.setBackground(anim);
// 获取动画资源
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
anim.start();
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
anim.stop();
}
});
}
}
和【Android】图形图像处理之“逐帧动画”(xml)的区别在哪呢?这是在java文件中处理的,当然会有一些区别。
比如:
【Android】图形图像处理之“逐帧动画”(xml)中获取动画资源只需要1步:final AnimationDrawable anim = (AnimationDrawable)animImg.getDrawable();
而在【Android】图形图像处理之“逐帧动画”(java)中就相对比较麻烦一点了:
final AnimationDrawable anim = new AnimationDrawable();
//先创建对象
anim.addFrame(getResources().getDrawable(R.drawable.horse1),50);
…
…
…
//添加帧
anim .setOneShot(false);
//设置无限循环
animImg.setBackground(anim);
//ImageView获取动画资源