How to capture Composable content as a Bitmap
masterCapturing Composable content involves three main steps:
- Initialize a Controller: Use the
rememberCaptureController()Composable function to create aCaptureControllerinstance. This controller manages the capture request. - Apply the Modifier: Apply the
Modifier.capturable(captureController)to the specific Composable component (or its parent container) that you want to convert into an image. - Trigger Capture: Call
captureController.captureAsync()within a coroutine scope. This method returns a deferred result that, when awaited, provides theImageBitmap.
@Composable
fun TicketScreen() {
val captureController = rememberCaptureController()
val scope = rememberCoroutineScope()
// 1. The content to be captured is wrapped in a container with the .capturable modifier
Column(modifier = Modifier.capturable(captureController)) {
MovieTicketContent(...)
}
Button(onClick = {
// 2. Trigger the capture asynchronously
scope.launch {
val bitmapAsync = captureController.captureAsync()
try {
val bitmap = bitmapAsync.await()
// Use the resulting ImageBitmap here
} catch (error: Throwable) {
// Handle capture errors
}
}
}) {
Text("Capture")
}
}