2012-12-07 52 views
0

为什么这不起作用?它按照应该打印的位置,但它不会移动屏幕上的图像?我正在使用模拟器。onDraw(画布画布)在使用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(); 
}  

}

回答

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); 
    } 
+0

图像仍然不动?有任何想法吗? – user1776707