Android Save View to Bitmap / Image File

If you are using Android-KTX, use drawToBitmap.

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

or without Android-KTX.

view.isDrawingCacheEnabled = trueval bitmap = view.drawingCacheview.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.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.