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

41

嗯,我正在学习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
    )
  }
}

1个回答

88

你可以在 Compose 中使用 Coil:

添加依赖项:

implementation("io.coil-kt:coil-compose:2.0.0-rc01")

然后像这样使用:

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

你好,对于如何使Image根据资源大小自动调整大小,你有什么建议吗?比如说,在下载远程图片之前我们不知道它的尺寸。 - Eugene
@Eugene,不要使用已定义大小的修饰符。 - goofy
我尝试了这个,但不幸的是运气不太好。我在Stack Overflow上发布了一个问题,如果你有时间可以看一下吗?https://dev59.com/9cHqa4cB1Zd3GeqP79HI - Eugene

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