簡體   English   中英

使用Android API在線程中使用onDraw(Canvas canvas)

[英]onDraw(Canvas canvas) in a thread using android API

為什么這不起作用? 它會按原樣打印位置,但不會在屏幕上移動圖像? 我正在使用模擬器。

我認為圖像應該四處移動,但是即使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();
}    

}

計算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);
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM