2011-10-23 34 views
2

我有一個SurfaceView這裏我設置背景顏色和像這樣的圖像:爲什麼畫布上的位圖出現在背景可繪製的下方?

BitmapDrawable tiledBackground = new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.background)); 
tiledBackground.setTileModeX(Shader.TileMode.REPEAT); 
tiledBackground.setColorFilter(0xaacceeff, PorterDuff.Mode.DST_OVER); 
this.setBackgroundDrawable(tiledBackground); 

我也有一個動畫線程在那裏我畫的圖像(連續的調整它的x座標,使其顯示移動到左側)。背景圖像是透明的PNG,因此它的某些部分是透明的。看來我正在從線程繪製的圖像出現在以下可在SurfaceView上繪製的背景。我如何讓它出現在背景之上?我繪製的圖像,像這樣:

private void doDraw(Canvas canvas) { 
    canvas.drawColor(Color.BLACK); 
    canvas.drawBitmap(missile, x, getHeight() - 95, paint); 
    canvas.restore(); 
} 

missilepaint在線程的構造函數初始化:

missile = Bitmap.createBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.missile)); 
paint = new Paint(); 
+0

可能無法正常工作,但嘗試在onDraw方法的開頭添加super.doDraw(canvas)。 –

+0

'doDraw'不是'Thread'的一部分,所以我不能調用'super.doDraw()'。 –

+0

對不起,我把你的doDraw和onDraw混在一起......我認爲它屬於擴展的Surfaceview。 doDraw在哪一類?你從哪裏打來的? –

回答

2

到doDraw每次調用應吸引你想要的一切顯示,包括的背景。

// Add to initializer 
tiledBackground = new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.background)); 
tiledBackground.setTileModeX(Shader.TileMode.REPEAT); 
tiledBackground.setColorFilter(0xaacceeff, PorterDuff.Mode.DST_OVER); 

private void doDraw(Canvas canvas) { 
    canvas.drawColor(Color.BLACK); 
    // Create a rectangle (just holds top/bottom/left/right info) 
    Rect drawRect = new Rect(); 

    // Populate the rectangle that we just created with the drawing area of the canvas. 
    canvas.getClipBounds(drawRect); 

    // Make the height of the background drawing area equal to the height of the background bitmap 
    drawRect.bottom = drawRect.top + tiledBackground.getBitmap().getHeight(); 

    // Set the drawing area for the background. 
    tiledBackground.setBounds(drawRect); 

    tiledBackground.draw(canvas); 
    canvas.drawBitmap(missile, x, getHeight() - 95, paint); 
    canvas.restore(); 
} 
+0

不幸的是,這隻給了我一個黑色的背景圖像。 –

+0

對不起,我放棄了setBounds調用。看看編輯後的版本是否適合你。 – goto10

+0

這工作*幾乎*完美。唯一的問題是它想要垂直拉伸圖像以適應屏幕。有沒有辦法阻止它做到這一點?你也可以添加一個關於'Rect','clipBounds'和'setBounds'的解釋嗎?謝謝! –

相關問題