I am trying to take a screenshot of a composable. ...
# compose-desktop
a
I am trying to take a screenshot of a composable. Someone a while back mentioned
ImageComposeScene
which works great. However, I cannot figure out how to take a screenshot after its images are loaded using Coil. Code in 🧵
1
Listening for Coil image requests:
Copy code
val requestCount = MutableStateFlow(0)

    setSingletonImageLoaderFactory { context ->
        val listener: coil3.EventListener = object : coil3.EventListener() {
            override fun onStart(request: ImageRequest) {
                super.onStart(request)
                println("onStart ${request.data}")
                requestCount.tryEmit(requestCount.value + 1)
            }

            override fun onCancel(request: ImageRequest) {
                super.onCancel(request)
                println("onCancel  ${request.data}")
                requestCount.tryEmit(requestCount.value - 1)
            }

            override fun onError(request: ImageRequest, result: ErrorResult) {
                super.onError(request, result)
                println("onError  ${request.data}")
                requestCount.tryEmit(requestCount.value - 1)
            }

            override fun onSuccess(request: ImageRequest, result: SuccessResult) {
                super.onSuccess(request, result)
                println("onSuccess  ${request.data}")
                requestCount.tryEmit(requestCount.value - 1)
            }
        }

ImageLoader.Builder(context).eventListener(listener)
// also applying disk + mem cache
.build()
Copy code
LaunchEffect(Unit){
    ImageComposeScene(width = 1200, height = 800) {
       ComposableWithAsyncImage()
    }.use { scene ->
        scene.render(Long.MAX_VALUE) // <- tried this to kick-off image loading

        println("Waiting until images are loaded. Request Count = ${requestCount.value}")
        requestCount.first { it == 0 }
        println("All images loaded. Taking screenshot Request Count = ${requestCount.value}")

        val image = scene.render(Long.MAX_VALUE)
        val data = image.encodeToData()!!

        Files.write(file.toPath(), data.bytes)
        println("Saved ${file.absolutePath}")
    } 
}
it saves the photo to disk but the image is not displayed. the count is correct though and i can see the logs waiting and finishing the loading. Oddly enough if i display the composable outside the imagecomposescene, wait for the image to load and then take the screenshot in the way above, the image loads
okay i figured it out. I can preload the images themselves via the
ImageLoader
before the screenshots instead of waiting for the UI to preload them. seems to be working