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

如何让Button内容显示在进度矩形上方?

解决Button进度填充遮挡文本的问题

按钮效果

我实现了一个带进度填充效果的Button,填充矩形会根据progress值变化,但现在Button里的Text被填充矩形遮挡了,给Text设置zIndex或者调整矩形透明度都没解决问题。

原代码如下:

Button(
  onClick = { /*TODO*/ },
  colors = ButtonDefaults.buttonColors(
    containerColor = Color(0xFF282828),
    contentColor = Color.White
  ),
  modifier = Modifier
    .height(50.dp)
    .fillMaxWidth()
    .drawWithContent {
      val w = size.width
      val h = size.height
      drawContent()
      clipRect(right = w * progress.value) {
        drawRoundRect(
          color = Color(0xFF634EFB).apply { this.copy(alpha = 0.38F) },
          cornerRadius = CornerRadius(x = 100.dp.toPx(), 100.dp.toPx()),
          size = Size(width = w, height = h),
          topLeft = Offset(0f, 0f),
        )
      }
    }
) {
  Text(text = "Hello")
}

解决方法

问题根源在drawWithContent的绘制顺序——先执行的绘制内容在底层,后执行的在顶层。你原来先调用drawContent()(绘制Text)再画填充矩形,导致填充层盖在Text上面。

只需要调换绘制顺序,先画填充矩形,再调用drawContent()就能让Text显示在填充层上方:

Button(
  onClick = { /*TODO*/ },
  colors = ButtonDefaults.buttonColors(
    containerColor = Color(0xFF282828),
    contentColor = Color.White
  ),
  modifier = Modifier
    .height(50.dp)
    .fillMaxWidth()
    .drawWithContent {
      val w = size.width
      val h = size.height
      // 先绘制进度填充矩形
      clipRect(right = w * progress.value) {
        drawRoundRect(
          color = Color(0xFF634EFB).copy(alpha = 0.38F),
          cornerRadius = CornerRadius(x = 100.dp.toPx(), 100.dp.toPx()),
          size = Size(width = w, height = h),
          topLeft = Offset(0f, 0f),
        )
      }
      // 再绘制Button的文本内容
      drawContent()
    }
) {
  Text(text = "Hello")
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 08:25:13