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?
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With