android - 如何从 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
)
}
}
解决方案
您可以使用 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)
)
推荐阅读
- arrays - 确定数组中的任何三个数字是否总和为特定值的最快方法是什么?
- c - bmp image_size 与 size 的区别
- google-apps-script - 您无权调用 UrlFetchApp
- c# - c# 嵌套循环 - 从 List 中获取不同的元素(没有 Linq)
- stock - 具有变体的股票价值导入 XML 提要
- python - 如何压缩json文件?
- python - AttributeError: 'list' 对象在代码中没有属性 'dtype' yolo_outputs = yolo_head(yolo_model.output, anchors, len(class_names))
- python-3.x - 如何使用 python 代码创建表
- reactjs - 在调度中检测到状态突变:即使使用工具包
- c - 状态流程图和 C 动作语言。设置数组值以在单个步骤中输出一个向量