2012-05-22 195 views
1

我使用这个代码来生成随机颜色(这是工作的罚款):生成随机颜色

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

我只是想知道如果有什么办法/组合只产生鲜艳的色彩?

谢谢

+2

您可以生成HSL/HSV颜色,然后转换为RGB。 http://en.wikipedia.org/wiki/HSL_and_HSV – Tom

回答

4

您的原始代码不起作用如你所期望的 - 如果产生一个低数字你可能会得到#1ffff(1为低红色值) - 这是无效的。它使用更稳定:

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

由于rgb(123,45,67)是完全有效的颜色规格。

与此相似,可以为HSL生成随机数:

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

这将产生完全饱和,任何色调的亮度正常颜色。但是,请注意,只有最近的浏览器支持HSL,因此如果浏览器支持受到关注,您可能更适合RGB。

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'; 
} 
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; 
} 
0

使用chakroun yesser的answer上面,我创造了这个功能:

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; 
}