Skip to content Skip to sidebar Skip to footer

Setting Image Background In Surfaceview, Getting Black Screen

Okay so Im trying to set the background of a SurfaceView to a JPG file. But it doesn't seem to want to draw the image, and all I get is a black screen. Here:s my code: public c

Solution 1:

First, you should implement SurfaceHolder.Callback interface with your MapView class and set it as a callback for its SurfaceHolder to make the app call your onSurfaceCreated() metod. Second, if you want your onDraw() method to be called, then call setWillNotDraw(false) in your MapView's constructor.

I've done that as following:

publicclassMapViewextendsSurfaceViewimplementsSurfaceHolder.Callback {

    private Bitmap scaled;

    publicMapView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setWillNotDraw(false);
        getHolder().addCallback(this);
    }

    publicvoidonDraw(Canvas canvas) {
        canvas.drawBitmap(scaled, 0, 0, null); // draw the background
    }

    @OverridepublicvoidsurfaceCreated(SurfaceHolder arg0) {
        Bitmapbackground= BitmapFactory.decodeResource(getResources(), R.drawable.dr);
        floatscale= (float) background.getHeight() / (float) getHeight();
        intnewWidth= Math.round(background.getWidth() / scale);
        intnewHeight= Math.round(background.getHeight() / scale);
        scaled = Bitmap.createScaledBitmap(background, newWidth, newHeight, true);
    }

    @OverridepublicvoidsurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        // TODO Callback method contents
    }

    @OverridepublicvoidsurfaceDestroyed(SurfaceHolder holder) {
        // TODO Callback method contents
    }
}

And it works well. NOTE: Moved MapView class to a separate *.java file. Update Watch Duplicate Copy Move

Post a Comment for "Setting Image Background In Surfaceview, Getting Black Screen"