Created
October 16, 2021 10:26
-
-
Save ch8n/1165e4fa3718fa6d052baaf1b3d7c8e9 to your computer and use it in GitHub Desktop.
Covert Composable into View then returns callback to get bitmap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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