PHP红色到绿色RGB颜色热图 [英] PHP Red to Green RGB Color Heatmap
问题描述
我似乎无法弄清楚.我有一组缩放的值(0 ... 1),需要将它们与颜色相关联.最高(1)为红色,最低(0)为绿色.
I can't seem to get this figured out. I have a scaled set of values (0...1) that I need to associate colors with. The highest (1) being red and the lowest (0) being green.
我似乎找不到如何获得介于0和1之间的值的红色和绿色之间的RGB颜色.
I cannot seem to find how to get an RGB color between red and green for a value that is between 0 and 1.
这是我要用于缩放值的缩放函数:
Here is my scaling function I am going to use to scale the values:
function scale_value($value, $srcmin, $srcmax, $destmin = 0, $destmax = 1)
{
# How Far In Source Range Are We
$pos = (($value - $srcmin) / ($srcmax - $srcmin));
return ($pos * ($destmax - $destmin)) + $destmin;
}
我认为将它们从0缩放到1将使下一个我正在苦苦挣扎的部分变得容易得多.
I figured scaling them from 0 to 1 will make the next part I am struggling with much easier.
这是我想出的一个非常糟糕的尝试,失败非常严重.
Here is one very crummy attempt at doing this I came up with, failed pretty badly.
function make_color($value)
{
$red = $value > 0.5
? (1 - 2 * ($value - 0.5) / 1)
: 1;
$green = $value > 0.5
? 1
: 2 * ($value / 1);
$blue = 0;
return "rgb($red,$green,$blue)";
}
是否有人有使用PHP来确定用于介于1和0之间的值的颜色的经验?
Does anyone have any experience using PHP to determine the color to use for a value that falls between 1 and 0?
推荐答案
Found a solution, converting the JS implemented solution posted here to PHP and reversing the Red to Green polarity so Red was high, Green was low.
看起来像这样:
/**
* @param $value
* @param integer|float $min
* @param integer|float $max
* @return string
*/
function make_color($value, $min = 0, $max = .5)
{
$ratio = $value;
if ($min > 0 || $max < 1) {
if ($value < $min) {
$ratio = 1;
} else if ($value > $max) {
$ratio = 0;
} else {
$range = $min - $max;
$ratio = ($value - $max) / $range;
}
}
$hue = ($ratio * 1.2) / 3.60;
$rgb = hsl_to_rgb($hue, 1, .5);
$r = round($rgb['r'], 0);
$g = round($rgb['g'], 0);
$b = round($rgb['b'], 0);
return "rgb($r,$g,$b)";
}
This also relies on an HSL to RGB translator, which I found on this post. This ends up giving me a pretty nice result:
感谢您的帮助.
这篇关于PHP红色到绿色RGB颜色热图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!