Android, canvas: How do I clear (delete contents of) a canvas (= bitmaps), living in a surfaceView?

samClem picture samClem · Apr 20, 2011 · Viewed 155.7k times · Source

In order to make a simple game, I used a template that draws a canvas with bitmaps like this:

private void doDraw(Canvas canvas) {
    for (int i=0;i<8;i++)
        for (int j=0;j<9;j++)
            for (int k=0;k<7;k++)   {
    canvas.drawBitmap(mBits[allBits[i][j][k]], i*50 -k*7, j*50 -k*7, null); } }

(The canvas is defined in "run()" / the SurfaceView lives in a GameThread.)

My first question is how do I clear (or redraw) the whole canvas for a new layout?
Second, how can I update just a part of the screen?

// This is the routine that calls "doDraw":
public void run() {
    while (mRun) {
        Canvas c = null;
        try {
            c = mSurfaceHolder.lockCanvas(null);
            synchronized (mSurfaceHolder) {
                if (mMode == STATE_RUNNING) 
                    updateGame();
                doDraw(c);          }
        } finally {
            if (c != null) {
                mSurfaceHolder.unlockCanvasAndPost(c);  }   }   }       }

Answer

Sileria picture Sileria · Jun 4, 2012

Draw transparent color with PorterDuff clear mode does the trick for what I wanted.

Canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)