3

我正在使用此代码生成随机颜色(工作正常):

  {
       $r = rand(128,255); 
       $g = rand(128,255); 
       $b = rand(128,255); 
       $color = dechex($r) . dechex($g) . dechex($b);
       return "#".$color;
  }

我只是想知道是否有一种方法/组合可以只生成明亮的颜色?

谢谢

4

4 回答 4

4

您的原始代码无法按预期工作 - 如果生成的数字较低,您可能会得到#1ffff(1 是低红色值) - 这是无效的。使用它更稳定:

echo "rgb(".$r.",".$g.",".$b.")";

因为rgb(123,45,67)是完全有效的颜色规范。

沿着类似的思路,您可以为 hsl 生成随机数:

echo "hsl(".rand(0,359).",100%,50%)";

这将生成任何色调的完全饱和的正常亮度颜色。但是,请注意,只有最近的浏览器支持 HSL,所以如果浏览器支持是一个问题,你最好选择 RGB。

于 2012-05-22T20:13:03.163 回答
3
function getRandomColor() {
    $rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
    $color = '#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];
    return $color;
}
于 2013-04-19T09:38:28.030 回答
2

我使用此代码检测背景颜色是浅色还是深色,然后选择正确的字体颜色,因此字体颜色在随机生成或用户输入的背景颜色上仍然可读/可见:

//$hex: #AB12CD
function ColorLuminanceHex($hex=0) {
  $hex = str_replace('#', '', $hex);
  $luminance = 0.3 * hexdec(substr($hex,0,2)) + 0.59 * hexdec(substr($hex,2,2)) + 0.11 * hexdec(substr($hex,4,2));
  return $luminance;
}


$background_color = '#AB12CD';
$luminance = ColorLuminanceHex($background_color);
if($luminance < 128) {
  $color = '#FFFFFF';
}
else {
  $color = '#000000';
}
于 2012-05-22T20:09:39.040 回答
0

使用上面 chakroun yesser 的回答,我创建了这个函数:

function generateRandomColor($count=1){
    if($count > 1){
        $color = array();
        for($i=0; $count > $i; $i++)
            $color[count($color)] = generateRandomColor();
    }else{
        $rand = array_merge(range(0, 9), range('a', 'f'));
        $color = '#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];
    }
    return $color;
}
于 2017-09-22T16:06:31.670 回答