[ Compose ] Load Async Image in Compose

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)) {}
    )
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值