androidbitmapandroid-jetpack-composecompose-multiplatformandroid-compose-image

How to get ImageBitmap from a Painter in Jetpack Compose?


I should use the Image() composable that takes image bitmap as its argument.

How can I convert a Painter to ImageBitmap in Compose?


Solution

  • 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
    }
    
    Usage:
    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)