Android Save View to Bitmap / Image File

July 12, 2019

If you are using Android-KTX, use drawToBitmap.

// val bitmap = view.toBitmap()
val bitmap = view.drawToBitmap()

or without Android-KTX.

view.isDrawingCacheEnabled = true
val bitmap = view.drawingCache
view.isDrawingCacheEnabled = false

or

fun toBitmapFromView(v: View): Bitmap {
    val b = Bitmap.createBitmap(v.layoutParams.width, v.layoutParams.height, Bitmap.Config.ARGB_8888)
    val c = Canvas(b)
    v.layout(v.left, v.top, v.right, v.bottom)
    v.draw(c)
    return b
}

If you happens to change Layout Width/Height programatically before converting the view to bitmap.

view.updateLayoutParams {
    this.width = newWidth
}

view.doOnLayout {
    val bitmap = view.drawToBitmap()
}

NOTE: Save bitmap to file.

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.