Andrew Raappana Andrew Raappana - 4 months ago 49
Android Question

Android Canvas to Bitmap

I have been searching online on how to turn what is on a canvas into a Bitmap. I have attempted multiple ways to do this like saving the drawing cache to a bitmap, but the end result is the background bitmap flashing on for a moment, then turning into a black screen. The test image is displayed over the background, but doesn't get overlaid by the background from the next calling of

OnDraw
.

MainThreading{

...

if(notuptodate == true){

//call readyBackground to create the background bitmap
this.mainPanel.readyBackground(canvas);
//post the canvas
surfaceHolder.unlockCanvasAndPost(canvas);
//clean the Canvas
canvas = null;
//ready new Canvas
canvas = this.surfaceHolder.lockCanvas();//lock the canvas to enable editing






}//if not true

if (MainThreading.notuptodate == false){

mainPanel.onDraw(canvas);


}//if false
...
}//mainthreading

//this method is run first to create the Bitmap that on draw will use
public void readyBackGround(Canvas canvas){


if (MainThreading.notuptodate){
//method used to draw multiple Bitmaps onto the canvas
renderBackground(canvas);

//private Bitmap, this is the supposed proper size of the bitmap
backgroundBitmap=Bitmap.createBitmap(240, 320, Config.ARGB_8888);


//set the canvas to turn whats on its self onto the bitmap.
canvas.setBitmap(backgroundBitmap);

//set boolean flag to false so renderBackground won't be called
//untill it needs to be updated again
MainThreading.notUpToDate = false;

}

//this method is called when notUpToDate = true
@Override
protected void onDraw(Canvas canvas){


if (this.threado.getBackground() != null){
canvas.drawBitmap(backgroundBitmap, 0, 0, null);

}

//this if statement is never activated
if (this.threado.getBackground() == null){
Log.d("background nonexistant", "Importante!");
}
//draw test object onto background
test.DrawObject(canvas);

//when MainThreading.notUpToDate = true isn't commented out, the
//screen consistantly shows the background, but the test object isn't
//drawn

//MainThreading.notUpToDate = true;





}

Answer

Try it this way...

- Create a bitmap of the correct size using Bitmap.createBitmap()

- Create a canvas instance pointing that this bitmap using Canvas(Bitmap) constructor

- Draw to the canvas

- Use the bitmap