这一篇来使用逐帧动画和补间动画来实现一个小例子,首先我们来看看Android中的补间动画。
Android中使用Animation代表抽象的动画类,该类包括下面几个子类:
AlphaAnimation:透明改变动画。
ScaleAnimation:大小缩放动画。
TranslateAnimation:位移变化动画。
RotateAnimation:旋转动画。
我们下面使用位移动画和逐帧动画来实现这个小例子,先看看运行效果:
蝴蝶挥动翅膀的逐帧动画文件:
android:oneshot="false">
android:oneshot="false">
界面布局文件:
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/background"
>
android:id="@+id/butterfly"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@anim/butteryfly"
/>
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/background"
>
android:id="@+id/butterfly"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@anim/butteryfly"
/>
具体逻辑及位移动画:
packagecom.example.butteryfly;
importjava.util.Timer;
importjava.util.TimerTask;
importandroid.app.Activity;
importandroid.graphics.drawable.AnimationDrawable;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.view.Display;
importandroid.view.View;
importandroid.view.View.OnClickListener;
importandroid.view.animation.TranslateAnimation;
importandroid.widget.ImageView;
publicclassMainActivityextendsActivity {
privatefloatcurX =0;
privatefloatcurY =30;
privatefloatnextX =0;
privatefloatnextY =0;
privateintwindowW =0;
privateintwindowH =0;
privateImageView imageView;
Handler handler = newHandler(){
publicvoidhandleMessage(android.os.Message msg) {
if(msg.what ==0x123){
if(nextX > windowW || nextY > windowH){
curX = nextX = 0;
}else{
nextX += 8;
}
nextY = curY + (float) (Math.random() *20-10);
TranslateAnimation anim = newTranslateAnimation(curX, nextX, curY, nextY);
curX = nextX;
curY = nextY;
anim.setDuration(200);
imageView.startAnimation(anim);
}
};
};
@Override
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.butterfly);
Display display = getWindowManager().getDefaultDisplay();
windowW = display.getWidth();
windowH = display.getHeight();
finalAnimationDrawable butterfly = (AnimationDrawable) imageView.getBackground();
imageView.setOnClickListener(newOnClickListener() {
@Override
publicvoidonClick(View arg0) {
butterfly.start();
newTimer().schedule(newTimerTask() {
@Override
publicvoidrun() {
handler.sendEmptyMessage(0x123);
}
}, 0,200);
}
});
}
}