Nat*_*han 4 java android android-canvas
我正在制作一个需要动态动画的应用程序。(玩家动作)我正在使用该Canvas对象来执行此操作。我的第一个问题是“Canvas真的是处理这些动画的最佳方法吗?”,我的第二个问题是“如何将玩家重新绘制到Canvas?” 这是我的代码:
theGame.java:
package birdprograms.freezetag;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
public class theGame extends Activity {
players[] arr = {
new player(),
new player(),
new player(),
new player()
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new myView(this));
}
public class myView extends View {
Paint paint = new Paint();
public myView(Context context) {
super(context);
paint.setColor(Color.YELLOW);
}
@Override
public void onDraw(final Canvas canvas) {
arr[0].update(true, true);
arr[0].draw(canvas, paint);
}
}
}
Run Code Online (Sandbox Code Playgroud)
播放器.java
package birdprograms.freezetag;
import android.graphics.*;
public class player {
int y = 0;
int x = 0;
int vy = 5;
int vx = 5;
int height = y + 15;
int width = x + 15;
public void draw(Canvas canvas, Paint paint){
canvas.drawRect(x,y,width,height,paint);
}
public void update(boolean left, boolean top){
if(left){x += vx; width = x + 15;}
else{x -= vx; width = x + 15;}
if(top){y += vy; height = y + 15;}
else{y -= vy; height = y + 15;}
}
}
Run Code Online (Sandbox Code Playgroud)
您实际上无法控制何时调用onDraw:当视图无效时,将onDraw在将来的某个时刻调用 。
您的代码中存在一个基本的设计缺陷:玩家的位置在执行期间被修改onDraw:您将无法控制它。
要每 5 秒移动一次玩家:您可以每 5 秒Handler.postDelayed重新发布一次相同内容Runnable。这Runnable将更新玩家位置,然后使视图无效。
这是一些代码来说明这个想法
(免责声明:这是伪代码,它只关心索引 0 处的玩家,要移动所有玩家还有更多工作要做,...)
public class myView extends View {
Paint paint = new Paint();
public myView(Context context) {
super(context);
paint.setColor(Color.YELLOW);
movePlayer0Runnable.run(); //this is the initial call to draw player at index 0
}
@Override
public void onDraw(final Canvas canvas) {
super.onDraw(canvas); //IMPORTANT to draw the background
arr[0].draw(canvas, paint);
}
Handler handler = new Handler(Looper.getMainLooper());
Runnable movePlayer0Runnable = new Runnable(){
public void run(){
arr[0].update(true, true);
invalidate(); //will trigger the onDraw
handler.postDelayed(this,5000); //in 5 sec player0 will move again
}
}
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6799 次 |
| 最近记录: |