我想在屏幕上爲角色設置動畫(例如運行狗)。 AnimationDrawable似乎非常適合這一點,而AnimationDrawable需要一個ImageView。如何在SurfaceView中添加和移動ImageView?SurfaceView中的Android動畫角色
謝謝。
我想在屏幕上爲角色設置動畫(例如運行狗)。 AnimationDrawable似乎非常適合這一點,而AnimationDrawable需要一個ImageView。如何在SurfaceView中添加和移動ImageView?SurfaceView中的Android動畫角色
謝謝。
使用SurfaceView,您有責任繪製其中的所有內容。你不需要AnimationDrawable或任何視圖來渲染你的角色。看看谷歌的示例遊戲Lunar Lander。
你不需要ImageView
。
如果你的動畫是一個XML Drawable
,您可以直接從Resources
加載到一個AnimationDrawable
變量:
Resources res = context.getResources();
AnimationDrawable animation = (AnimationDrawable)res.getDrawable(R.drawable.anim);
然後將其設置的界限,並在畫布上繪製:也
animation.setBounds(left, top, right, bottom);
animation.draw(canvas);
你需要手動將動畫設置爲在下一個計劃時間間隔運行。這可以通過使用animation.setCallback
創建新的回調,然後實例化android.os.Handler
並使用handler.postAtTime
方法將下一個動畫幀添加到當前的Thread
的消息隊列來實現。
animation.setCallback(new Callback() {
@Override
public void unscheduleDrawable(Drawable who, Runnable what) {
return;
}
@Override
public void scheduleDrawable(Drawable who, Runnable what, long when) {
//Schedules a message to be posted to the thread that contains the animation
//at the next interval.
//Required for the animation to run.
Handler h = new Handler();
h.postAtTime(what, when);
}
@Override
public void invalidateDrawable(Drawable who) {
return;
}
});
animation.start();
有沒有理由不重用Handler? – RichieHH
感謝Burov,所以AnimationDrawable不適合遊戲嗎? – droidbee
是的。 AnimationDrawable不是視圖,您可以按照nmelo的說明使用它。 – RichieHH