如何从 Jetpack Compose 中的 URL 加载图像? [英] How to load image from URL in Jetpack Compose?

查看:134
本文介绍了如何从 Jetpack Compose 中的 URL 加载图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Well, I am studying the Compose UI and I am stucking in basic things. One of them is show a image from URL with Glide.

我尝试了以下代码,但没有调用委托(onResourceReady 和 onLoadCleared).

I have tried the below code but the delegates (onResourceReady and onLoadCleared) are not being called.

我错过了什么吗?

@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
    )
  }
}

推荐答案

你可以使用 Coil 来编写:

You can use Coil for compose:

添加依赖:

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)
)

这篇关于如何从 Jetpack Compose 中的 URL 加载图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆