如何从 Jetpack Compose 中的 URL 加载图像?

LMa*_*ker 10 android android-glide android-jetpack-compose

好吧,我正在研究 Compose UI,并且我一直在学习基本的东西。其中之一是使用 Glide 显示来自 URL 的图像。

我已经尝试了下面的代码,但没有调用委托(onResourceReady 和 onLoadCleared)。

我错过了什么?

@Composable
fun loadPicture(url: String, contentDescription:String, modifier: Modifier = Modifier) {

  val bitmapState = remember { mutableStateOf<Bitmap?>(null) }
  Glide.with(LocalContext.current).asBitmap().load(url).into(
    object : CustomTarget<Bitmap>() {
        override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
            bitmapState.value = resource
        }
        override fun onLoadCleared(placeholder: Drawable?) {}
    }
)

  bitmapState.value?.let {
    Image(
        contentDescription = contentDescription,
        bitmap = it.asImageBitmap(),
        modifier = modifier
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

ngl*_*ber 13

您可以使用 Coil 进行组合:

添加依赖:

implementation("io.coil-kt:coil-compose:1.3.1")
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

implementation("io.coil-kt:coil-compose:1.3.1")
Run Code Online (Sandbox Code Playgroud)