0

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:

  1. Enabled drawingCache for the view.
  2. Used Canvas to draw the view into a Bitmap.

I want to capture the view as a Bitmap so I can later save it as an image or share it.

1 Answer 1

0

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.