Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create bitmap from view makes view disappear, how to get view canvas?

I found two ways of creating a Bitmap from a view. But once I do that, the view disappears and I can't use it anymore. How can I redraw the view after generating my bitmap?

1st:

public static Bitmap getBitmapFromView(View view) {
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
Drawable bgDrawable =view.getBackground();
if (bgDrawable!=null) 
    bgDrawable.draw(canvas);
else 
    canvas.drawColor(Color.WHITE);
view.draw(canvas);
return returnedBitmap;
}

2nd:

Bitmap viewCapture = null;

theViewYouWantToCapture.setDrawingCacheEnabled(true);

viewCapture = Bitmap.createBitmap(theViewYouWantToCapture.getDrawingCache());

theViewYouWantToCapture.setDrawingCacheEnabled(false);

EDIT

So, I think I understand what happens on the first one, we are basically removing the view from it's original canvas and drawing it somewhere else associated with that bitmap. Can somehow we store the original canvas and then set the view to be redrawn there?

like image 616
caiocpricci2 Avatar asked Oct 05 '22 06:10

caiocpricci2


2 Answers

Sorry, I'm not immensely knowledgeable on this. But I use the following code:

public Bitmap getBitmapFromView(View view, int width, int height) {
    Bitmap returnedBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(returnedBitmap);
    Drawable bgDrawable = view.getBackground();
    if (view==mainPage.boardView) { 
        canvas.drawColor(BoardView.BOARD_BG_COLOR);
    } else if (bgDrawable!=null) { 
        bgDrawable.draw(canvas);
    } else { 
        canvas.drawColor(Color.WHITE);
    }
    view.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
    view.layout(0, 0, width, height); 
    view.draw(canvas);
    return returnedBitmap;
}

which is so similar to yours I suspect we copy&edited from the same place.

I have no trouble with the view disappearing from the original drawing tree. Mine is called for ViewGroups rather than plain Views.

like image 116
Guy Smith Avatar answered Oct 10 '22 01:10

Guy Smith


Try this.

Getting the bitmap:

// Prepping.
boolean oldWillNotCacheDrawing = view.willNotCacheDrawing();
view.setWillNotCacheDrawing(false); 
view.setDrawingCacheEnabled(true);
// Getting the bitmap
Bitmap bmp = view.getDrawingCache();

And make sure to reset the view back to its old self.

view.destroyDrawingCache();
view.setDrawingCacheEnabled(false);
view.setWillNotCacheDrawing(oldWillNotCacheDrawing);    

return bmp; 
like image 26
Streets Of Boston Avatar answered Oct 10 '22 03:10

Streets Of Boston