Bitmap から ImageBitmap への変換には Bitmap.asImageBitmap() を使います。
@Preview
@Composable
fun SampleScreen() {
val density = LocalDensity.current
val layoutDirection = LocalLayoutDirection.current
val bitmap = remember { mutableStateOf<Bitmap?>(null) }
Column {
Button(
onClick = {
bitmap.value = createBitmap(density, layoutDirection)
},
modifier = Modifier.padding(16.dp)
) {
Text(text = "click")
}
AndroidView(
factory = { context ->
ImageView(context)
},
update = { imageView ->
imageView.setImageBitmap(bitmap.value)
},
modifier = Modifier.padding(16.dp)
)
androidx.compose.foundation.Canvas(
modifier = Modifier.padding(16.dp)
.size(with(LocalDensity.current) { 512.toDp() })
) {
val bmp = bitmap.value
if (bmp != null) {
drawImage(bmp.asImageBitmap())
drawCircle(Color.White, radius = size.minDimension / 4f)
}
}
}
}
private fun createBitmap(
density: Density,
layoutDirection: LayoutDirection
): Bitmap {
val targetSize = 512
val imageBitmap = ImageBitmap(targetSize, targetSize)
val size = Size(targetSize.toFloat(), targetSize.toFloat())
CanvasDrawScope().draw(density, layoutDirection, Canvas(imageBitmap), size) {
drawCircle(Color.Red)
}
return imageBitmap.asAndroidBitmap()
}