Assuming a drawing app that allows users to export a canvas, or a simple image editing app that users can share the edited photo, there might be limited ways to convert a composable to a bitmap.

In this post, I will share my experience of using standard methods to convert a composable into a bitmap and store it as a PNG in internal storage.
According to official docs you can access the view version of your composable function using LocalView.current
, and export that view to a bitmap file like this (the following code goes inside the composable function):
val view = LocalView.current
val context = LocalContext.current
val handler = Handler(Looper.getMainLooper())
handler.postDelayed(Runnable {
val bmp = Bitmap.createBitmap(view.width, view.height,
Bitmap.Config.ARGB_8888).applyCanvas {
view.draw(this)
}
bmp.let {
File(context.filesDir, "screenshot.png")
.writeBitmap(bmp, Bitmap.CompressFormat.PNG, 85)
}
}, 1000)
The writeBitmap
method is a simple extension function for File class. Example:
private fun File.writeBitmap(bitmap: Bitmap, format: Bitmap.CompressFormat, quality: Int) {
outputStream().use { out ->
bitmap.compress(format, quality, out)
out.flush()
}
}
If you liked this approach, vote for the stackoverflow post. Looking forward to read your feedback soon! π