首页 > 解决方案 > 如何从 Jetpack Compose 中的 URL 加载图像?

问题描述

好吧,我正在研究 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
    )
  }
}

标签: androidandroid-glideandroid-jetpack-compose

解决方案


您可以使用 Coil 进行撰写:

添加依赖:

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

并像这样使用它:

Image(
    painter = rememberImagePainter("https://www.example.com/image.jpg"),
    contentDescription = null,
    modifier = Modifier.size(128.dp)
)

推荐阅读