我試圖製作一個遊戲,在不同位置有許多相同圖像的實例。我希望只聲明一次圖像,然後在onDraw()中使用該位圖。但是,當我使用在類中聲明的任何類型的變量時,我會得到一個錯誤,因爲它會保留它的值。 我剛轉移到使用surfaceview,所以也許我錯過了一些東西。我目前只是想繪製一張圖片,但這個想法是一樣的,一旦我開始使用多個實例,就會使用它。 我現在所擁有的:在surfaceview的onDraw上高效地繪製同一圖像的多個實例
class GameView extends SurfaceView implements SurfaceHolder.Callback
{
private GameThread _thread;
// vars for display, scale, etc
private int displayWidth;
private int displayHeight;
private double scale;
private Bitmap groundPic;
public GameView(Context context) {
super(context);
// set the surface holder for callback
getHolder().addCallback(this);
_thread = new GameThread(getHolder(), this);
displayWidth = getWidth();
displayHeight = getHeight();
scale = displayWidth/512.0; // ground image is 512;
}
@Override
public void onDraw(Canvas canvas)
{
groundPic = BitmapFactory.decodeResource(getResources(), R.drawable.ground);
groundPic = Bitmap.createScaledBitmap(groundPic, displayWidth, 50, true);
canvas.drawColor(getResources().getColor(R.color.background_colour));
// draw ground
canvas.drawBitmap(groundPic,0, getHeight() - 50, null);
}
這會導致強制關閉,因爲displayWidth爲0。我錯了,在構造函數中設置值是多少?我嘗試創建一個init(),在創建視圖之後並在setContentView()之前從我的活動中調用。 我知道它的作品,如果我把所有的設置內onDraw(),但我覺得它真的效率低下。 我希望做的事情(但造成的錯誤)是有init()和內部,設置groundPic這將是一個類變量,然後我的onDraw會小而快,因爲它不會繼續每個週期都有相同的位圖對象。我也會在地面上繪製30枚導彈,因此,如果我只能製作一次,然後在特定位置繪製30次,每個週期製作30個相同的位圖將是一項巨大的浪費。 如果任何人都可以幫助我指出正確的方向,以正確地工作,它將不勝感激。
非常感謝你!我決定嘗試處理程序和Runnables,到目前爲止工作正常,但在接下來的遊戲中,我一定會嘗試SurfaceView(使用相對佈局來設置所有位置的工作比所需的更多)。 偉大的指針,我真的很感激它。 – 2012-04-28 03:53:24