我有一个 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();
}
missile
和 paint
在线程的构造函数中被初始化为:
missile = Bitmap.createBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.missile));
paint = new Paint();
最佳答案
每次调用 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();
}
关于android - 为什么我在 Canvas 上的位图出现在背景可绘制对象下方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7864040/