Hello, everyone! I try to capture the bitmap of a ...
# compose
k
Hello, everyone! I try to capture the bitmap of a composable container, using
DrawModifierNode
. The problem is that the
ContentDrawScope.draw()
won't be called when scrolling or clicking children (displaying ripples), unless recomposition happens. Is my way correct to get the bitmap? I want to get the bitmap when the view changes every time.
Copy code
override fun ContentDrawScope.draw() {
    println("draw")
    val graphicsContext = requireGraphicsContext()
    val layer = graphicsContext.createGraphicsLayer()
    layer.record {
        drawRect(Color.White)
        this@draw.drawContent()
    }
    coroutineScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
        val bitmap = layer.toImageBitmap().asAndroidBitmap()
        graphicsContext.releaseGraphicsLayer(layer)
    }
    drawContent()
}
s
You can use OnPreDrawListener from ViewTreeObserver, which you can obtain from the current View. Here’s an example of how I’m using it for a similar purpose. However, capturing a bitmap on every frame isn’t ideal, as it’s a memory-intensive operation. If your goal is to record the screen, the MediaProjection API is a more suitable solution.
(if you’re asking about compose on Android)
k
Thank you very much, it works as my expectations.