Running Pig,顾名思义就是“奔跑的猪”,就是一个小猪从屏幕左边奔跑至右边(草坪),再从右边奔跑至左边,循环往复。
这是我之前在网上学习时学到的一个有趣的动画,写下来跟大家分享一下~:
首先要让小猪在草坪上奔跑,需要有草坪的图片,然后还要有小猪的图片:
将图片导入Demo中,要让小猪的腿动起来需要使用逐帧动画,而要让小猪奔跑进行位移的话则要使用补间动画。
1.首先定义逐帧动画的XML文件放置于drawable文件夹中,并设置每个静态画面对应的资源及时长:
pig_toleft.xml:
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/pig3" android:duration="50"/> <item android:drawable="@drawable/pig4" android:duration="50"/> </animation-list>
pig_toright.xml:
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/pig1" android:duration="50"/> <item android:drawable="@drawable/pig2" android:duration="50"/> </animation-list>2.在布局文件中放置小猪图片资源,还有草坪图片作为背景颜色:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="@mipmap/background" tools:context="com.shen.Running Pig.MainActivity"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ivPig" android:layout_marginTop="200dp" android:background="@drawable/pig_toright"/> </LinearLayout>
3.接着就是要让小猪跑动起来啦:
public class MainActivity extends AppCompatActivity { private ImageView ivPig; private TranslateAnimation toRightAnim; private TranslateAnimation toLeftAnim; private AnimationDrawable animationDrawable; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
ivPig = (ImageView) findViewById(R.id.ivPig);
//让小猪的腿动起来 animationDrawable = (AnimationDrawable) ivPig.getBackground(); animationDrawable.start(); //向右平移的动画设置 toRightAnim = new TranslateAnimation(0,1000,0,0); toRightAnim.setDuration(2000); //向左平移的动画设置 toLeftAnim = new TranslateAnimation(1000,0,0,0); toLeftAnim.setDuration(2000); //监听小猪向右平移的动作 toRightAnim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } //当动画结束后自动触发该方法 @Override public void onAnimationEnd(Animation animation) {
//当小猪向右平移结束后将小猪的方向转换成向左 ivPig.setBackgroundResource(R.drawable.pig_toleft); //小猪的腿动起来 animationDrawable.start(); //开始向左移动 ivPig.startAnimation(toLeftAnim); } @Override public void onAnimationRepeat(Animation animation) { } }); //监听小猪向左平移的动作 toLeftAnim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) {
//在小猪向左平移结束后再将其方向转换成向右 ivPig.setBackgroundResource(R.drawable.pig_toright); animationDrawable = (AnimationDrawable) ivPig.getBackground(); animationDrawable.start(); ivPig.startAnimation(toRightAnim); } @Override public void onAnimationRepeat(Animation animation) { } }); ivPig.startAnimation(toRightAnim); } }好啦,这样做好以后就可以看到小猪在草坪上左右左右来回跑动啦~