onDraw(Canvas canvas)在一个使用android API的线程中

时间:2012-12-07 01:34:03

标签: java android

为什么这不起作用?它打印的位置应该但它不会移动屏幕上的图像?我正在使用模拟器。

我认为图像应该四处移动,但即使x和y值发生变化,它也会保持在同一个位置。我认为问题可能是我在调用onDraw(画布)时使用的画布。我该怎么做才能使它工作(如果画布是问题)?

如果这还不够详细请告诉我。代码如下;

  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();
}    

}

1 个答案:

答案 0 :(得分:0)

在计算x和y坐标后,应将对象放回画布上。

public void onDraw(Canvas canvas) { 
    canvas.drawColor(Color.BLACK);  
    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;
    }
    canvas.drawBitmap(bmp, x, y, null);
  }