I should use the Image()
composable that takes image bitmap as its argument.
How can I convert a Painter
to ImageBitmap
in Compose?
Here is a solution from the asBitmap()
function in Compose Multiplatform fork:
fun Painter.toImageBitmap(
size: Size,
density: Density,
layoutDirection: LayoutDirection,
): ImageBitmap {
val bitmap = ImageBitmap(size.width.toInt(), size.height.toInt())
val canvas = Canvas(bitmap)
CanvasDrawScope().draw(density, layoutDirection, canvas, size) {
draw(size)
}
return bitmap
}
val myPainter = ...
val size = myPainter.intrinsicSize // OR, for example, Size(300f, 100f)
val density = LocalDensity.current // OR, for example, Density(1f, 1f)
val direction = LocalLayoutDirection.current // OR, for example, LayoutDirection.Ltr
val myImageBitmap = myPainter.toImageBitmap(size, density, direction)