Reputation: 15
I'm building an Android app in Kotlin, and I want to capture a particular View (like a TextView or ImageView) as a Bitmap. I’ve read that DrawingCache can help with this, but I’m unsure if it’s the best approach. I need the bitmap to save or share as an image later.
Here’s what I’ve tried so far:
I want to capture the view as a Bitmap so I can later save it as an image or share it.
Upvotes: 0
Views: 34
Reputation: 1472
DrawingCache
is an option, it’s outdated, and the preferred method now is to use a Bitmap
and Canvas
to capture the view's contents.
Kotlin Code
fun captureViewAsBitmap(view: View): Bitmap {
// Create a bitmap with the same width and height as the view
val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
// Draw the view onto the canvas, which will render it to the bitmap
view.draw(canvas)
return bitmap
}
Java Code
public Bitmap captureViewAsBitmap(View view) {
// Create a bitmap with the same width and height as the view
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
// Draw the view onto the canvas, which will render it to the bitmap
view.draw(canvas);
return bitmap;
}
Upvotes: 0