为什么这不起作用?它按应有的方式打印位置,但不会在屏幕上移动图像?我正在使用模拟器。
我认为图像应该四处移动,但即使 x 和 y 值发生变化,它也会保持在同一个地方。我认为问题可能是我调用 onDraw(canvas) 时使用的画布。我可以对这个画布做些什么来使它工作(如果画布是问题)?
如果这还不够详细,请告诉我。下面的代码;
GameView.java
package com.example.game;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.View;
public class GameView extends View implements Runnable{
Thread gameLoop = new Thread(this);
boolean running = false;
int x = 10;
int y = 10;
Canvas canvas = new Canvas();
private Bitmap bmp;
public GameView(Context context) {
super(context);
bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
}
@Override
public void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(bmp, x, y, null);
System.out.println(x);
if(x < 100) {
x+=10;
}
if(x >= 99 && y < 400) {
y+=10;
}
if(y > 350 && x >= 99) {
x = 10;
y = 10;
}
}
public void start() {
if(!running) {
running = true;
gameLoop.start();
}
}
public void stop() {
if(running) {
running = false;
}
}
@Override
public void run() {
while(running) {
try{
onDraw(canvas);
Thread.sleep(1000);
}catch(Exception exc) {System.err.println("error sleep interup");}
}
}
}
Main.java
package com.example.game;
import android.app.Activity;
import android.os.Bundle;
public class Main extends Activity {
GameView gv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gv = new GameView(this);
setContentView(gv);
gv.start();
}
}