Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How dynamically change images in SurfaceView?

I am using default SurfaceView implementation, code can be found here(this is a finger drawing app example, I just disabled that and drawn an image). There are 3 main separate classes -

  1. An Activity Class (SurfaceViewSampleActivity)
  2. SurfaceView (CanvasView)
  3. Thread class (UIThread).

SurfaceView draws image(Bitmap) which is set in constructor. I also implemented functionality where user can call Camera app and take a picture. Picture has to swap default image (on SurfaceView constructor set image).

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

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

}

I thought that SurfaceView thread could be using bitmap so I tried to lock the variable:

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

App also crashes.

SurfaceView draw 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 any way to change the bitmap variable in SurfaceView after the constructor has been called?

like image 430
user2003066 Avatar asked Jan 24 '13 12:01

user2003066


1 Answers

What does your run method look like. I would take a look at the Lunar Lander sample. You need to lock and unlock the canvas.

    @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);
                }
            }
        }
    }
like image 157
Nathan Avatar answered Oct 22 '22 23:10

Nathan