我为此花了几个小时,想节省别人几个小时。
此函数采用百分比值并计算RGB颜色。 这对于希望背景或其他指标根据该值更改的图形或表格很有用。
我大部分时间都花在的问题上是黄色的消失。
该代码已记录在案,应该易于理解。 发表对此帖子的任何疑问或修改。
执照:
GPL公开
/**
* Example of use of percent2Color function
* @author Dan M
* @date 06/24/2010
*
*
*/
/**
* This function takes a value and returns an RGB color between Red to Yellow to Green in a given spectrum.
* 50% = FFFF00
*
* @param mixed $value required
* @param mixed $brightness value between 1 and 255
* @param mixed $max default 100
* @param mixed $min default 0
* @param mixed $thirdColorHex '00'
*/
function percent2Color($value,$brightness = 255, $max = 100,$min = 0, $thirdColorHex = '00')
{
// Calculate first and second color (Inverse relationship)
$first = (1-($value/$max))*$brightness;
$second = ($value/$max)*$brightness;
// Find the influence of the middle color (yellow if 1st and 2nd are red and green)
$diff = abs($first-$second);
$influence = ($brightness-$diff)/2;
$first = intval($first + $influence);
$second = intval($second + $influence);
// Convert to HEX, format and return
$firstHex = str_pad(dechex($first),2,0,STR_PAD_LEFT);
$secondHex = str_pad(dechex($second),2,0,STR_PAD_LEFT);
return $firstHex . $secondHex . $thirdColor ;
// alternatives:
// return $thirdColorHex . $firstHex . $secondHex;
// return $firstHex . $thirdColorHex . $secondHex;
}
该代码is肿,使初学者更容易理解。
我知道我可以偷工减料。
它还需要进行一些错误检查(例如,亮度必须在1到255之间)。
如果您想压缩或添加它,请继续并将新版本发布回去! 如果需要,您还可以将受影响的对从红绿色更改为绿蓝色或蓝红色,并选择红色或绿色。
干杯,
丹·M
使用示例:
<html>
<body>
<table width="300px">
<tr><td>Percent</td><td>Color</td></tr>
<?php
$example = array(10,40,28,69,100,0,50);
foreach($example as $x)
{
$color = percent2Color($x,$brightness = 200);
echo "<tr><td>$x</td><td style='background-color:#$color'>$color</td>";
}
?>
</table>
</body>
</html>
</html>
From: https://bytes.com/topic/php/insights/890539-how-produce-first-pair-rgb-hex-color-value-percent-value