Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);  }   }   }       } 
like image 412
samClem Avatar asked Apr 20 '11 11:04

samClem


People also ask

How do you clear a bitmap?

You can use eraseColor on bitmap to set its color to Transparent. It will useable again without recreating it. cleanest solution.

What is bitmap in canvas?

Canvas is the place or medium where perfroms/executes the operation of drawing, and Bitmap is responsible for storing the pixel of the picture you draw.


2 Answers

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

Canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR) 
like image 66
Sileria Avatar answered Nov 15 '22 22:11

Sileria


How do I clear (or redraw) the WHOLE canvas for a new layout (= try at the game) ?

Just call Canvas.drawColor(Color.BLACK), or whatever color you want to clear your Canvas with.

And: how can I update just a part of the screen ?

There is no such method that just update a "part of the screen" since Android OS is redrawing every pixel when updating the screen. But, when you're not clearing old drawings on your Canvas, the old drawings are still on the surface and that is probably one way to "update just a part" of the screen.

So, if you want to "update a part of the screen", just avoid calling Canvas.drawColor() method.

like image 27
Wroclai Avatar answered Nov 15 '22 23:11

Wroclai