|
| 1 | +package de.berlindroid.zepatch.utils |
| 2 | + |
| 3 | +import androidx.compose.foundation.background |
| 4 | +import androidx.compose.foundation.clickable |
| 5 | +import androidx.compose.foundation.layout.Box |
| 6 | +import androidx.compose.runtime.Composable |
| 7 | +import androidx.compose.runtime.LaunchedEffect |
| 8 | +import androidx.compose.runtime.getValue |
| 9 | +import androidx.compose.runtime.mutableStateOf |
| 10 | +import androidx.compose.runtime.remember |
| 11 | +import androidx.compose.runtime.rememberCoroutineScope |
| 12 | +import androidx.compose.runtime.setValue |
| 13 | +import androidx.compose.ui.Modifier |
| 14 | +import androidx.compose.ui.draw.drawWithContent |
| 15 | +import androidx.compose.ui.graphics.Color |
| 16 | +import androidx.compose.ui.graphics.ImageBitmap |
| 17 | +import androidx.compose.ui.graphics.rememberGraphicsLayer |
| 18 | +import kotlinx.coroutines.launch |
| 19 | + |
| 20 | +/** |
| 21 | + * Composable utility that renders [content] into a compositing graphics layer and can |
| 22 | + * capture it into an [ImageBitmap]. |
| 23 | + * |
| 24 | + * How it works: |
| 25 | + * - We draw the composable's content into a remembered graphics layer using drawWithContent. |
| 26 | + * - We then draw that content normally so it appears on screen. |
| 27 | + * - We can capture the current pixels of that layer via graphicsLayer.toImageBitmap(). |
| 28 | + * |
| 29 | + * Behavior: |
| 30 | + * - If [autoCapture] is true, it will capture once on first composition and invoke [onBitmap]. |
| 31 | + * - It also supports manual capture by tapping the content (clickable), which will invoke [onBitmap]. |
| 32 | + */ |
| 33 | +@Composable |
| 34 | +fun CaptureToBitmap( |
| 35 | + modifier: Modifier = Modifier, |
| 36 | + onBitmap: (ImageBitmap) -> Unit, |
| 37 | + content: @Composable () -> Unit, |
| 38 | +) { |
| 39 | + val coroutineScope = rememberCoroutineScope() |
| 40 | + val graphicsLayer = rememberGraphicsLayer() |
| 41 | + |
| 42 | + Box( |
| 43 | + modifier = modifier |
| 44 | + .drawWithContent { |
| 45 | + // Record content drawing into the graphics layer |
| 46 | + graphicsLayer.record { |
| 47 | + this@drawWithContent.drawContent() |
| 48 | + } |
| 49 | + } |
| 50 | + .clickable { |
| 51 | + coroutineScope.launch { |
| 52 | + val bitmap = graphicsLayer.toImageBitmap() |
| 53 | + onBitmap(bitmap) |
| 54 | + } |
| 55 | + } |
| 56 | + .background(Color.White) |
| 57 | + ) { |
| 58 | + content() |
| 59 | + } |
| 60 | +} |
0 commit comments