2013-04-10 97 views
1

因此,我正在努力使每天的標題更改顏色,並且我試圖使用隨機顏色來創建此顏色。標題中有2種顏色,我正在製作免費的顏色。第一種顏色是隨機生成的,然後第二種顏色是通過150`改變色調來修改的。問題是選擇某些顏色時,它們可能太亮或太暗。我有一個檢查運行,以便我可以稍微控制亮度值,但仍然有一些顏色太亮(例如極端黃色)。我會在下面發佈我的代碼。任何幫助或建議表示讚賞!謝謝!用php隨機生成顏色

// grab a random color on hue 
$h = rand(0,360); 

// color values 50-120 tend to be extremely bright, 
// make adjustments to the S and L accordingly 
// a better solution is available? 
if ($h > 50 && $h < 120) { 
    $s = rand(60,80); 
    $l = rand(30,50); 
} else { 
    $s = rand(60,90); 
    $l = rand(38,63); 
} 

// declare string to place as css in file for primary color   
$randomColor = "hsl(". $h .",". $s ."%,". $l ."%)"; 

// declare degree for secondary color (30 = analogous, 150 = complimentary) 
$degree = 150; 

// point to secondary color randomly on either side of chart   
$bool = rand(0,1); 
if ($bool) { 
    $x = $degree; 
} else { 
    $x = -$degree; 
} 

// set value of the new hue 
$nh = $h + $degree; 

// if the new hue is above 360 or below 0, make adjustments accordingly 
if ($nh > 360) { 
    $nh -= 360; 
} 
if ($nh < 0) { 
    $nh = 360 - $nh; 
} 

// set the secondary color 
$secondaryColor = "hsl(". abs($h + $x) .",". $s ."%,". $l ."%)"; 

這看起來很簡單,我確信有更好的方法。我環顧四周,但所有我注意到的是色調等基本公式的度數等。再次感謝!

+5

你爲什麼不只是使用一個顏色值的數組,並使用'array_rand()' – Oussama 2013-04-10 15:37:35

+0

我對色彩理論並不是很好,但如果你只是擔心色彩在H/S/L色彩空間中太亮/暗你只是把L值的上限和下限? – Sammitch 2013-04-10 16:06:39

回答

1

這實際上更多的是你認爲哪些顏色可以接受查看的問題。這當然不是一個最佳的解決方案,但它是一個辦法,是可讀的,至少(這也是比原來的更隨機,如果你更在乎的是):

function randColor() { 
    return array(rand(0,360), rand(0,100), rand(0,100)); 
} 

function isAcceptableColor($colorArr) { 
    // return true if the color meets your criteria 
} 

do { 
    $color = randColor(); 
} while (! isAcceptableColor($color)); 
+0

我相信你的意思是'while(!isAcceptableColor($ color))',不是嗎? – nibra 2013-04-10 16:26:18

+0

我確定:)如果我沒有把這個評論放在'isAcceptableColor'方法中,我可能會以「這取決於函數返回的內容」的藉口離開了,但你得到了我。謝謝 – 2013-04-10 17:32:27