Set SurfaceView Background Image

Is there a way to set the surfaceview background image? Do I need to do this in xml or can I do it all in Java - I have something similar to this in my constructor:

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

But he still shows nothing.

+5
source share
4 answers

You cannot set a wallpaper on a SurfaceView. You will have to draw the background on the surface yourself.

+3
source

As long as you cannot directly set the background image to SurfaceView, you can overlap ImageView(displaying the background image) and yours SurfaceViewon top of it, making it transparent.

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); 

SurfaceView : ( "" SurfaceView)

canvas.drawColor(0, PorterDuff.Mode.CLEAR);
+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
}
+4

A small addition to xav's answer. After that, you want to set the content view as rootPanel:

setContentView(rootPanel);

Also, since FILL_PARENT is deprecated, consider using MATCH_PARENT in both places.

0
source

All Articles