如何在 Jetpack Compose 中从资产中加载图像

4

我在assets文件夹中有数百个png文件,我想将它们加载到Image组件中。但是我只能使用drawable文件夹中的图像。 如何从assets中加载图像到Image中?

2个回答

4

例子:

var bitmapState by remember{ mutableStateOf<Bitmap?>(null) }
val context = LocalContext.current

LaunchedEffect(Unit) {
    bitmapState = BitmapFactory.decodeStream(context.assets.open("assetsImage.png"))
}


if (null != bitmapState) {
    val bitmap = bitmapState!!.asImageBitmap()
    Image(
        bitmap = bitmap,
        "assetsImage",
        modifier = Modifier.fillMaxSize(),
        colorFilter = null
    )
}

2

@Halifax 的解决方案可以行得通,但它的性能存在一些问题。使用 Coil 会更加顺畅和清晰。

在 build.gradle (:app) 文件中:

implementation("io.coil-kt:coil-compose:2.2.2")

然后:

AsyncImage(
            model = "file:///android_asset/images_folder/image.png",
            contentDescription = "",
        )

我试图展示一个SVG文件,但它没有显示出来 - 有什么帮助吗? - VFarkas2023

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接