如何在 Jetpack Compose 中从 URL 加载图像?
How to load image from URL in 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
)
}
}
您可以使用 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)
)
好吧,我正在学习 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 进行合成:
添加依赖:
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)
)