Jetpack Compose how to create an ImageBitmap with specific size and configurations?

Viewed 2983

ImageBitmap loads and image with

ImageBitmap.imageResource(
        LocalContext.current.resources,
        R.drawable.landscape1
    )

also it there is a function which can be invoked with some parameters

ImageBitmap(
        width = 300,
        height = 300,
        config = ImageBitmapConfig.Argb8888,
        hasAlpha = true,
        colorSpace = ColorSpaces.Srgb
    )

it returns and empty bitmap with no pixel data, is it possible to create an imageBitMap with some specific configurations?

Is there something like for ImageBitmap?

val option = BitmapFactory.Options()
option.inPreferredConfig = Bitmap.Config.ARGB_8888
val bitmap: Bitmap = BitmapFactory.decodeResource(
    LocalContext.current.resources,
    R.drawable.landscape1,
    option
)
1 Answers

You can convert Bitmap to ImageBitmap:

val option = BitmapFactory.Options()
option.inPreferredConfig = Bitmap.Config.ARGB_8888
val bitmap = BitmapFactory.decodeResource(
    LocalContext.current.resources,
    R.drawable.test,
    option
).asImageBitmap()

Note, that it'll take significant amount of time on each recomposition, so you'd probably want to wrap it with remember

Related