You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose中为加载中的GlideImage添加渐变占位

解决Jetpack Compose中GlideImage加载时仅显示渐变状态的问题

你当前的方案会让渐变背景一直存在于图片下方,导致透明PNG加载后透出渐变,不符合仅加载时显示的需求。可以通过Accompanist Glide组件提供的loading参数来实现仅在加载阶段显示渐变,具体实现如下:

实现步骤

  1. 确保已引入Accompanist Glide依赖(版本需与你的Compose版本适配):
implementation "com.google.accompanist:accompanist-glide:<latest-version>"
  1. 使用GlideImage的loading参数自定义加载时的渐变UI:
// 定义渐变brush
val gradientBrush = Brush.linearGradient(listOf(Gray, Color.White))

GlideImage(
    model = banner.imageUrl,
    contentDescription = null,
    contentScale = ContentScale.FillHeight,
    modifier = Modifier.coloredShadow(ShadowBannerImage, 0.28f),
    // 加载状态时显示渐变背景
    loading = {
        Box(
            modifier = Modifier
                .matchParentSize()
                .background(brush = gradientBrush)
        )
    }
)

原理说明

  • loading参数接收一个@Composable函数,仅在图片加载过程中渲染该UI,加载完成后会自动替换为目标图片。
  • 这种方式避免了渐变背景长期存在于图片下方的问题,完美适配透明PNG的场景。

备选方案(手动管理加载状态)

如果你需要更精细的状态控制,可以通过rememberGlidePainter监听加载状态,手动控制渐变层的显示:

val gradientBrush = Brush.linearGradient(listOf(Gray, Color.White))
val glidePainter = rememberGlidePainter(
    request = banner.imageUrl,
    fadeIn = true
)
val isLoading = glidePainter.state is PainterState.Loading

Box(modifier = Modifier.coloredShadow(ShadowBannerImage, 0.28f)) {
    // 仅加载中时显示渐变
    if (isLoading) {
        Box(
            modifier = Modifier
                .matchParentSize()
                .background(brush = gradientBrush)
        )
    }
    // 显示图片
    Image(
        painter = glidePainter,
        contentDescription = null,
        contentScale = ContentScale.FillHeight,
        modifier = Modifier.matchParentSize()
    )
}

内容的提问来源于stack exchange,提问作者R0ck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 19:51:02