设置SurfaceView的背景图像

Han*_*ney 7 java android background-image surfaceview drawable

有没有办法设置SurfaceView的背景图像?是否必须在xml中完成,或者我可以用Java完成所有操作 - 我的构造函数中有一些看起来像这样的东西:

Drawable sky = (getResources().getDrawable(R.drawable.sky));
    this.setBackgroundDrawable(sky);
Run Code Online (Sandbox Code Playgroud)

但它仍然没有显示任何东西.

xav*_*xav 7

虽然您无法直接将背景图像设置为a SurfaceView,但您可以重叠ImageView(显示背景图像)和您的背景图像SurfaceView,使其透明.

绘制一个1920x1080位图作为每个SurfaceView重绘的背景图像时,我遇到了性能问题:我找到的唯一解决方案(感谢这个答案)是使用ImageView显示这个1920x1080(固定)位图,并使用我SurfaceView的顶部,制作它透明,避免为每次SurfaceView重绘绘制大背景图像.现在我的应用程序更顺畅,多亏了这段代码:

// Setup your SurfaceView
SurfaceView surfaceView = ...;  // use any SurfaceView you want
surfaceView.setZOrderOnTop(true);
surfaceView.getHolder().setFormat(PixelFormat.TRANSPARENT);

// Setup your ImageView
ImageView bgImagePanel = new ImageView(context);
bgImagePanel.setBackgroundResource(...); // use any Bitmap or BitmapDrawable you want

// Use a RelativeLayout to overlap both SurfaceView and ImageView
RelativeLayout.LayoutParams fillParentLayout = new RelativeLayout.LayoutParams(
    RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
RelativeLayout rootPanel = new RelativeLayout(context);
rootPanel.setLayoutParams(fillParentLayout);
rootPanel.addView(surfaceView, fillParentLayout); 
rootPanel.addView(bgImagePanel, fillParentLayout); 
Run Code Online (Sandbox Code Playgroud)

然后你应该SurfaceView用这个开始你的绘画方法:(为了"刷新" SurfaceView缓冲区中先前绘制的图像)

canvas.drawColor(0, PorterDuff.Mode.CLEAR);
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你,兄弟!2 天我正在努力做到这一点!5年后,这仍然挽救了某人的生命。 (2认同)
  • 非常感谢...`canvas.drawColor(0, PorterDuff.Mode.CLEAR);` 是离合器! (2认同)

Man*_*dan 6

试试这个

public void surfaceCreated(SurfaceHolder arg0) {
    Bitmap background = BitmapFactory.decodeResource(getResources(), R.drawable.background);
    float scale = (float)background.getHeight()/(float)getHeight();
    int newWidth = Math.round(background.getWidth()/scale);
    int newHeight = Math.round(background.getHeight()/scale);
    Bitmap scaled = Bitmap.createScaledBitmap(background, newWidth, newHeight, true);
}

public void onDraw(Canvas canvas) {
    canvas.drawBitmap(scaled, 0, 0, null); // draw the background
}
Run Code Online (Sandbox Code Playgroud)


Rom*_*Guy 5

您无法在SurfaceView上设置可绘制的背景。您必须自己将背景绘制到表面上。