android 如何将合成视图转换为位图?

jogvjijk  于 2023-03-16  发布在  Android
关注(0)|答案(2)|浏览(135)

我有一个简单的活动,我正在使用它来转换composeViewBitmap
然而,当我运行下面的myBitmap是空白的,并没有显示“你好”的文本组合。
我怎样才能让下面的composeView转换为位图?

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*/
    }
}
km0tfn4u

km0tfn4u1#

你必须等到视图布置好

viewTreeObserver.addOnGlobalLayoutListener(object : OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                val bitmap = graphicUtils.createBitmapFromView(view = view, width = width, height = height)
                onBitmapCreated(bitmap)
                viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        })

取自https://proandroiddev.com/create-bitmaps-from-jetpack-composables-bdb2c95db51

pw9qyyiw

pw9qyyiw2#

您缺少此代码setContentView(composeView)

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)
            )
        }
        // Without this code, you need to render to the activity to take a screenshot
        setContentView(composeView)

        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*/
    }
}

相关问题