How to dynamically change images in SurfaceView?

I use the default implementation of SurfaceView, the code can be found here (this is an example of a finger painting application, I just turned it off and drew an image). There are 3 main separate classes -

  • Activity Class ( SurfaceViewSampleActivity )
  • SurfaceView ( CanvasView )
  • Theme class ( UIThread ).

SurfaceView draws an image (bitmap) that is set in the constructor. I also implemented functionality in which the user can call the Camera application and take a picture. The image should change the default image (on the installation image of the SurfaceView constructor).

I tried to create a simple method in my activity class and set the bitmap, but this did not work:

private void setImage() {
    view.bitmap = this.mImageBitmap; 

}

I thought that a SurfaceView stream could use a bitmap, so I tried to lock the variable:

private void setImage() {   
    synchronized (view.bitmap) {
        view.bitmap = this.mImageBitmap;
    }   
}

The application also crashes.

SurfaceView Drawing Method:

protected void onDraw(Canvas canvas) {
    setPaintProperties();

    if (canvas != null) {
        canvas.drawColor(Color.WHITE);

        synchronized ( this.bitmap ) {
            canvas.drawBitmap(this.bitmap, 0, 0, new Paint() );
        }

    }
}

Is there a way to change the bitmap variable in SurfaceView after called by the constructor?

+5
source share
1 answer

. . .

    @Override
    public void run() {
        while (mRun) {
            Canvas c = null;
            try {
                c = mSurfaceHolder.lockCanvas(null);
                synchronized (mSurfaceHolder) {
                    if (mMode == STATE_RUNNING) updatePhysics();
                    doDraw(c);
                }
            } finally {
                // do this in a finally so that if an exception is thrown
                // during the above, we don't leave the Surface in an
                // inconsistent state
                if (c != null) {
                    mSurfaceHolder.unlockCanvasAndPost(c);
                }
            }
        }
    }
0

All Articles