Skip to content

Instantly share code, notes, and snippets.

@ch8n
Created October 16, 2021 10:26
Show Gist options
  • Save ch8n/1165e4fa3718fa6d052baaf1b3d7c8e9 to your computer and use it in GitHub Desktop.
Save ch8n/1165e4fa3718fa6d052baaf1b3d7c8e9 to your computer and use it in GitHub Desktop.
Covert Composable into View then returns callback to get bitmap
@Composable
fun CaptureBitmap(
content: @Composable () -> Unit,
): () -> Bitmap {
val context = LocalContext.current
/**
* ComposeView that would take composable as its content
* Kept in remember so recomposition doesn't re-initialize it
**/
val composeView = remember { ComposeView(context) }
/**
* Callback function which could get latest image bitmap
**/
fun captureBitmap(): Bitmap {
return composeView.drawToBitmap()
}
/** Use Native View inside Composable **/
AndroidView(
factory = {
composeView.apply {
setContent {
content.invoke()
}
}
}
)
/** returning callback to bitmap **/
return ::captureBitmap
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment