【问题标题】:Why does my bitmap on the canvas appear below the background drawable?为什么我在画布上的位图出现在背景可绘制对象下方?
【发布时间】:2011-10-23 02:52:24
【问题描述】:

我有一个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();

【问题讨论】:

  • 可能行不通,但请尝试在 onDraw 方法的开头添加 super.doDraw(canvas)。
  • doDraw 不是Thread 的一部分,所以我不能打电话给super.doDraw()
  • 哦,对不起,我把你的 doDraw 和 onDraw 混在一起了……我以为它属于扩展的 Surfaceview。 doDraw 在什么类?你从哪里叫它?
  • 别担心! doDraw 在一个名为 AnimationThread 的类中,它扩展了 Thread。我从我的线程的run() 方法中调用它。
  • 当你调用doDraw时,你从哪里得到画布?

标签: android canvas surfaceview


【解决方案1】:

对 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();
}

【讨论】:

  • 不幸的是,这只是给了我一个黑色的背景图像。
  • 抱歉,我停止了 setBounds 调用。看看修改后的版本是否更适合您。
  • 几乎完美地工作。唯一的问题是它想垂直拉伸图像以适应屏幕。有没有办法阻止它这样做?您还可以解释一下RectclipBoundssetBounds 的作用吗?谢谢!
  • 您需要将 setTileModeX 更改为 setTileModeXY 以便它在两个方向上平铺。我会用这个更新答案并回答你的其他问题。
  • 我不希望它在 Y 方向平铺。该图像是一幅风景画,只能在 X 方向平铺。感谢您花时间回答我的问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-20
  • 2018-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多