设置 SurfaceView 的背景图像
有没有办法设置SurfaceView的背景图片?它是否必须在 xml 中完成,或者我可以在 Java 中完成这一切吗?我的构造函数中有一些看起来像这样的东西:
Drawable sky = (getResources().getDrawable(R.drawable.sky));
this.setBackgroundDrawable(sky);
但它仍然没有显示任何内容。
Is there a way to set the background image of a SurfaceView? Does it have to be done in xml or can I do it all in Java - I've got something that looks like this in my constructor:
Drawable sky = (getResources().getDrawable(R.drawable.sky));
this.setBackgroundDrawable(sky);
But it still doesn't show anything.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对 xav 答案的一个小补充。之后您需要将内容视图设置为 rootPanel:
此外,由于 FILL_PARENT 已弃用,请考虑在这两个地方使用 MATCH_PARENT。
A small addition to the answer by xav. You'd want to set the content view as rootPanel afterwards:
Also, since FILL_PARENT is deprecated, consider using MATCH_PARENT in both places.
虽然您无法直接为
SurfaceView
设置背景图像,但您可以将ImageView
(显示背景图像)和SurfaceView
重叠在在此之上,使其透明。在为每个 SurfaceView 重绘绘制 1920x1080 位图作为背景图像时,我遇到了性能问题:我找到的唯一解决方案(感谢 这个答案)使用
ImageView
显示这个1920x1080(固定)位图,并在它上面使用我的SurfaceView
,使其透明,以避免每次SurfaceView
重新绘制时绘制大背景图像。现在,我的应用程序更加流畅,这要归功于这段代码:然后您应使用以下代码启动
SurfaceView
的绘制方法:(以便“刷新”SurfaceView
中先前绘制的图像代码>的缓冲区)While you can't directly set a background image to a
SurfaceView
, you can overlap anImageView
(displaying your background image) and yourSurfaceView
on top of this, making it transparent.I had performances issues when drawing a 1920x1080 bitmap as a background image for each SurfaceView repaint: the only solution I found (thanks to this answer) was using an
ImageView
displaying this 1920x1080 (fixed) bitmap, and using mySurfaceView
on top of it, making it transparent, to avoid painting the big background image for eachSurfaceView
repaint. Now my app is much smoother, thanks to this code:Then you shall start your
SurfaceView
's paint method with this: (in order to "flush" the previous drawn image inSurfaceView
's buffer)您无法在 SurfaceView 上设置背景可绘制对象。您必须自己将背景绘制到表面上。
You cannot set a background drawable on a SurfaceView. You'll have to draw the background onto the surface yourself.