Krystian Kaniowski
09/13/2022, 8:51 AMKrystian Kaniowski
09/13/2022, 8:53 AMKrystian Kaniowski
09/13/2022, 9:08 AMspierce7
09/13/2022, 2:22 PMImageComposeScene
is the way to do this. It’s pretty easy to use, but it does have a bug if you are hitting this from multiple threads at the same time. I’ve worked around it in the mean time with a lock.
Rendering the image is where 95% of the work is done in the screenshoting process, which happens outside of the mutex.
private val IMAGE_COMPOSE_SCENE_MUTEX = Mutex()
/**
* Because of a bug, ImageComposeScene has issues while being run in parallel, even though they shouldn't impact each
* other. Most of the work seems to be done outside the scene when the image is rendered anyway, so not much is
* lost by protecting this with a mutex.
*
* <https://github.com/JetBrains/compose-jb/issues/1396>
*/
suspend fun SafeImageComposeScene(
width: Int,
height: Int,
density: Density = Density(1f),
coroutineContext: CoroutineContext = Dispatchers.Unconfined,
content: @Composable () -> Unit = {},
): ImageComposeScene {
return IMAGE_COMPOSE_SCENE_MUTEX.withLock {
ImageComposeScene(
width = width,
height = height,
density = density,
coroutineContext = coroutineContext,
content = content
)
}
}