【问题标题】:PHP - Generate color from Green -> Black -> RedPHP - 从绿色生成颜色 -> 黑色 -> 红色
【发布时间】:2017-05-28 00:49:03
【问题描述】:

在 PHP 中,我有一个值从 0 到 1 以及介于两者之间的所有值的列表。我想为每个值赋予它自己的颜色。

我希望 0 为绿色,0.5 为黑色,1 为红色。像 0.1 这样的值应该仍然是绿色的,但开始稍微渐变为黑色。像 0.6 这样的值将是黑色,偏向红色。

我尝试使用来自:Generate colors between red and green for a power meter? 的 RGB 方法

$R = (255 * $percentage) / 100;
$G = (255 * (100 - $percentage)) / 100 ;
$B = 0;

但这会直接在绿色和红色之间创建一种颜色,而我不能在中间使用黑色。

我尝试将 HSL 转为 RGB:HSL to RGB color conversion

/**
* Converts an HSL color value to RGB. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes h, s, and l are contained in the set [0, 1] and
* returns r, g, and b in the set [0, 255].
*
* @param   {number}  h       The hue
* @param   {number}  s       The saturation
* @param   {number}  l       The lightness
* @return  {Array}           The RGB representation
*/
function hslToRgb(h, s, l){
    var r, g, b;

    if(s == 0){
        r = g = b = l; // achromatic
    }else{
        var hue2rgb = function hue2rgb(p, q, t){
            if(t < 0) t += 1;
            if(t > 1) t -= 1;
            if(t < 1/6) return p + (q - p) * 6 * t;
            if(t < 1/2) return q;
            if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
            return p;
        }

        var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
        var p = 2 * l - q;
        r = hue2rgb(p, q, h + 1/3);
        g = hue2rgb(p, q, h);
        b = hue2rgb(p, q, h - 1/3);
    }

    return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
}

但这会产生从绿色到白色再到红色的颜色。我希望它从绿色变为黑色再到红色。无论如何我可以完成这项工作吗?

【问题讨论】:

  • 您为一个用 PHP 标记的问题发布了 Javascript 代码。您确定您没有使用 Javascript 来执行此操作吗?
  • 哦,是的,对不起。我只是将它转换为 PHP,相同的代码现在只有变量用于 php。

标签: php colors rgb hsl


【解决方案1】:

像这样简单的事情应该可以解决问题:

$R = 0;
$G = 0;
$B = 0;

// 255 ÷ 50 = 5.1
if($percentage > 50) {
    $R = 5.1 * ($percentage - 50);
} 
elseif($percentage < 50) {
    $G = 255 - (5.1 * $percentage);
}

编辑

请注意,如果您使用 Javascript 或 PHP,elseif/else if 的写法会有所不同。当前示例适用于 PHP,因为它是您的问题被标记的内容。

【讨论】:

  • 我只需要稍作调整以更好地满足我的需求,但这个想法确实有效。谢谢!我想得太难了。
  • 我的荣幸! :)
猜你喜欢
  • 1970-01-01
  • 2018-09-15
  • 2012-08-04
  • 2021-07-07
  • 2011-05-08
  • 1970-01-01
  • 1970-01-01
  • 2011-10-28
  • 1970-01-01
相关资源
最近更新 更多