如何从JetpackCompose中的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
)
}
}
回答
您可以使用 Coil 进行组合:
- https://coil-kt.github.io/coil/compose/
添加依赖:
implementation("io.coil-kt:coil-compose:1.3.1")
并像这样使用它:
implementation("io.coil-kt:coil-compose:1.3.1")