2012-05-22 191 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; 
}