2011-05-12 90 views
5

有没有办法设置SurfaceView的背景图像?是否有在XML来完成,或者我可以做到这一切在Java中 - 我已经得到的东西,看起来像这样在我的构造函数:设置SurfaceView的背景图像

Drawable sky = (getResources().getDrawable(R.drawable.sky)); 
    this.setBackgroundDrawable(sky); 

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

回答

3

您不能在SurfaceView上设置可绘制背景。你必须自己将背景绘制到表面上。

+0

好的,那么在onDraw()方法中,我会假设? – 2011-05-12 16:28:19

+0

不,onDraw()不会做你想要的。在使用SurfaceView时,您可以使用OpenGL上下文渲染它,也可以通过SurfaceHolder抓取曲面的Canvas。你必须使用Canvas渲染你的背景(如果你正在做OpenGL,则使用OpenGL) – 2011-05-12 16:30:21

+1

我只使用Canvas - 我只是想弄清楚如何使用Canvas做到这一点。 – 2011-05-12 16:31:47

4

试试这个

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 
} 
+1

如何我可以给布局大小的位图在画布上绘制,并将其放置在surfaceview的中心。 – 2015-04-30 04:36:12

6

虽然你不能直接在背景图片设置为SurfaceView,您可以在此之上的ImageView(显示你的背景图像)和你的SurfaceView重叠,使之透明。

我有表演的问题画一个1920×1080的位图作为每个SurfaceView重绘背景图像时:唯一的解决办法,我发现(感谢this answer)使用的ImageView显示这1920×1080(固定)的位图,并在上面用我的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); 

就要把“这个paint方法:(为了在SurfaceView以‘刷新’先前绘制的图像”启动SurfaceView小号缓冲)

canvas.drawColor(0, PorterDuff.Mode.CLEAR); 
+0

谢谢你的男人! 2天我试图做到这一点! 5年后这仍然救人一命。 – 2016-12-12 14:13:57

+1

非常感谢...'canvas.drawColor(0,PorterDuff.Mode.CLEAR);''是离合! – annie 2017-02-08 19:23:03

0

xav答案的一小部分。你会想以后设置内容视图rootPanel:

setContentView(rootPanel); 

而且,由于FILL_PARENT已过时,考虑在这两个地方使用MATCH_PARENT。