有没有办法设置 SurfaceView 的背景图像?它必须在 xml 中完成还是我可以在 Java 中全部完成 - 我的构造函数中有一些看起来像这样的东西:
Drawable sky = (getResources().getDrawable(R.drawable.sky));
this.setBackgroundDrawable(sky);
但它仍然没有显示任何内容。
最佳答案
虽然您不能直接将背景图像设置到 SurfaceView
,但您可以重叠 ImageView
(显示您的背景图像)和您的 SurfaceView
在此之上,使其透明。
在为每个 SurfaceView 重绘绘制 1920x1080 位图作为背景图像时,我遇到了性能问题:我找到的唯一解决方案(感谢 this answer)是使用显示此 1920x1080 的 ImageView
(已修复)位图,并在其顶部使用我的 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);
然后你应该开始你的 SurfaceView
的绘制方法:(为了“刷新” SurfaceView
的缓冲区中之前绘制的图像)
canvas.drawColor(0, PorterDuff.Mode.CLEAR);
关于java - 设置 SurfaceView 的背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5981098/