Introduce Coil3
implementation("io.coil-kt.coil3:coil-compose:3.0.2")
implementation("io.coil-kt.coil3:coil-network-okhttp:3.0.2")
Load Web Image
@Preview
@Composable
fun AsyncImageView() {
AsyncImage(
model = "https://www.sanguosha.cn/new_index_pc/img/sgs_code.jpg", contentDescription = null,
modifier = Modifier.background(Color.Yellow).width(300.dp).height(300.dp)
)
}
Extend Image Painter
you can manually define what to display, depend on image loading state
@Preview
@Composable
fun AsyncImageView() {
SubcomposeAsyncImage(
model = "https://www.sanguosha.cn/new_index_pc/img/sgs_code.jpg", contentDescription = null,
modifier = Modifier.background(Color.Yellow).width(300.dp).height(300.dp)
) {
val isSuccess = painter.state.collectAsState().value is AsyncImagePainter.State.Success
if (isSuccess)
SubcomposeAsyncImageContent(modifier = Modifier.scale(0.8f))
else
Image(painter = painterResource(x.android.commons.R.drawable.ic), null)
}
}
Load Without AsyncImage
both AsyncImageView and SubcomposeAsyncImage are implemented through custom painter
we can directly get it through coil apis, without using AsyncImageView
@Preview
@Composable
fun AsyncImageView() {
val asyncImagePainter = rememberAsyncImagePainter("https://www.sanguosha.cn/new_index_pc/img/sgs_code.jpg")
val interactionSource = remember { MutableInteractionSource() }
println(asyncImagePainter)
Image(
painter = asyncImagePainter, contentDescription = null,
modifier = Modifier.background(Color.Yellow).width(300.dp).height(300.dp)
.clickable(interactionSource = interactionSource, indication = ripple(color = Color.Red)) {}
)
}