Compose-Coil基础上手
创始人
2024-05-25 11:53:55
0

准备阶段

Coil与Glide、Picasso为三大图片库

Coil 官方中文文档:https://coil-kt.github.io/coil/README-zh/

下载依赖:

// 原生
implementation("io.coil-kt:coil:2.2.2")// compose
implementation("io.coil-kt:coil-compose:2.2.2")

由于 Coil 使用 okhttp 请求,故需要在 manifest.xml 添加网络权限:


分步快速上手

全部参考官方文档并做精简处理


AsyncImage

图片会自适应所有布局

可根据当前盒子大小按照原比例拉伸图片,并保证图片宽度占满整个盒子宽度(在不对 AsyncImage 设置任何 modifier 的情况下)

@Composable
fun CoilBasic(){// 异步加载网络图片,使用内置okhttp请求// 这是一张普通的苹果图片AsyncImage(model = "https://img0.baidu.com/it/u=4" +"023062467,4103551361&fm=253&fmt=auto&app=1" +"38&f=JPEG?w=650&h=434",contentDescription = null)
}

或者直接在 Image 组件中使用

rememberAsyncImagePainter 接收图片 URL 作为参数

@Composable
fun CoilImage(){Image(...painter = rememberAsyncImagePainter(model = IMAGE_URL),contentDescription = null)
}

更深入的 AsyncImage 配置

@Composable
fun CoilAsyncDefine(){AsyncImage(// ImageRequest.Builder构建自定义图片显示方式model = ImageRequest.Builder(LocalContext.current).data("https://pic-go-bed.oss-cn-beijing.aliyuncs.com/img/20220316151929.png").crossfade(true).build(),// 其他的不怎么重要的设置contentDescription = stringResource(R.string.description),placeholder = painterResource(id = R.drawable.place_holder),error = painterResource(id = R.drawable.error),onSuccess = {Log.d(TAG, "success")})
}

SubcomposeAsyncImage

该组件为 AsyncImage 的变体,可以轻易地通过 loading 属性设置加载时动画

SubcomposeAsyncImage(model = "https://example.com/image.jpg",loading = {CircularProgressIndicator()},contentDescription = stringResource(R.string.description)
)

可以直接检查 painter 状态实现更复杂的逻辑

SubcomposeAsyncImage(model = "https://example.com/image.jpg",contentDescription = stringResource(R.string.description)
) {val state = painter.stateif (state is AsyncImagePainter.State.Loading || state is AsyncImagePainter.State.Error) {CircularProgressIndicator()} else {SubcomposeAsyncImageContent()}
}

AsyncImagePainter

若无法使用 AsyncImage 组件,可以使用 AsyncImagePainter 代替

val painter = rememberAsyncImagePainter(model = ImageRequest.Builder(LocalContext.current).data("https://pic-go-bed.oss-cn-beijing.aliyuncs.com/img/20220316151929.png").build()
)
if (painter.state is AsyncImagePainter.State.Loading) {CircularProgressIndicator()
}
Image(painter = painter,contentDescription = stringResource(R.string.description)
)

相关内容

热门资讯

监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
修复 爱普生 EPSON L4... L4151 L4153 L4156 L4158 L4163 L4165 L4166 L4168 L4...
【PdgCntEditor】解... 一、问题背景 大部分的图书对应的PDF,目录中的页码并非PDF中直接索引的页码...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...
MFC文件操作  MFC提供了一个文件操作的基类CFile,这个类提供了一个没有缓存的二进制格式的磁盘...