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

如何根据进度值动态改变Progress Bar的颜色?

进度条红-黄-绿渐变效果实现方案

这个需求完全可行,核心思路是根据进度值(0-100)动态计算对应的颜色值,或者利用渐变背景配合进度调整显示区域。以下是几种常见技术栈的实现方式:

Web 前端实现

方法1:CSS 渐变背景 + 动态位置调整

通过定义覆盖两倍宽度的红-黄-绿线性渐变,再根据进度值调整背景位置,让进度条显示的区域匹配当前进度对应的颜色:

<div class="progress-bar" style="--progress: 60; width: 60%"></div>
.progress-bar {
  height: 20px;
  border-radius: 10px;
  background: linear-gradient(to right, red, yellow 50%, green);
  background-size: 200% 100%; /* 让渐变覆盖两倍宽度,方便平移 */
  background-position: calc((100 - var(--progress)) * 1%) 0;
}

进度更新时,通过 JS 修改 --progress 变量即可:

const updateProgress = (progress) => {
  const bar = document.querySelector('.progress-bar');
  bar.style.width = `${progress}%`;
  bar.style.setProperty('--progress', progress);
};

方法2:JS 动态计算 RGB 颜色值

根据进度分两段计算颜色分量:

  • 0-50:红色保持255,绿色从0递增到255(红→黄)
  • 50-100:绿色保持255,红色从255递减到0(黄→绿)
function getProgressColor(progress) {
  let r, g;
  if (progress <= 50) {
    r = 255;
    g = Math.floor((progress / 50) * 255);
  } else {
    r = Math.floor(((100 - progress) / 50) * 255);
    g = 255;
  }
  return `rgb(${r}, ${g}, 0)`;
}

// 使用示例
const progressBar = document.querySelector('.progress-bar');
progressBar.style.width = `${currentProgress}%`;
progressBar.style.backgroundColor = getProgressColor(currentProgress);

Android 平台实现(Kotlin)

通过计算 RGB 颜色值,给 ProgressBar 的进度层设置颜色滤镜:

fun getProgressColor(progress: Int): Int {
    val r: Int
    val g: Int
    if (progress <= 50) {
        r = 255
        g = (progress / 50f * 255).toInt()
    } else {
        r = ((100 - progress) / 50f * 255).toInt()
        g = 255
    }
    return Color.rgb(r, g, 0)
}

// 进度更新时调用
progressBar.progress = currentProgress
progressBar.progressDrawable.setColorFilter(
    getProgressColor(currentProgress),
    PorterDuff.Mode.SRC_IN
)

iOS 平台实现(Swift)

自定义进度颜色计算逻辑,设置 ProgressView 的进度 tint 颜色:

func getProgressColor(progress: Float) -> UIColor {
    var r: CGFloat, g: CGFloat
    if progress <= 0.5 {
        r = 1.0
        g = progress / 0.5
    } else {
        r = (1.0 - progress) / 0.5
        g = 1.0
    }
    return UIColor(red: r, green: g, blue: 0.0, alpha: 1.0)
}

// 进度更新时调用
progressView.progress = currentProgress
progressView.progressTintColor = getProgressColor(progress: currentProgress)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 14:58:35