我应该使用以图像位图作为参数的
Image()
可组合项。
如何在 Compose 中将
Painter
转换为 ImageBitmap
?
这是 Compose Multiplatform fork 中此文件中的
asBitmap()
函数的解决方案:
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)