Home:ALL Converter>How to convert a ComposeView to Bitmap?

How to convert a ComposeView to Bitmap?

Ask Time:2022-10-31T05:34:29         Author:mars8

Json Formatter

I have a simple activity which I am using to convert a composeView to Bitmap.

However when I run the below myBitmap is blank and does not show the "Hello" text composable.

How can I make the below convert composeView to Bitmap?

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val widthPx = 200
        val heightPx = 120

        val composeView = ComposeView(applicationContext)
        composeView.setContent {
            Text(
                text = "Hello",
                color = Color.Black,
                fontSize = 14.sp,
                modifier = Modifier
                    .wrapContentSize()
                    .background(Color.Green)
            )
        }

        val myBitmap: Bitmap = Bitmap.createBitmap(widthPx,heightPx,Bitmap.Config.ARGB_8888)

        val myCanvas = Canvas(myBitmap) 
        composeView.draw(myCanvas)
        val result = myBitmap /*<--- result is blank bitmap*/
    }
}

Author:mars8,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/74256929/how-to-convert-a-composeview-to-bitmap
yy