用php随机生成颜色
因此,我正在努力使每天的标题更改颜色,并且我试图使用随机颜色来创建此颜色。标题中有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 ."%)";
这看起来很简单,我确信有更好的方法。我环顾四周,但所有我注意到的是色调等基本公式的度数等。再次感谢!
这实际上更多的是你认为哪些颜色可以接受查看的问题。这当然不是一个最佳的解决方案,但它是一个办法,是可读的,至少(这也是略比原来的更随机,如果你更在乎的是):
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));
我相信你的意思是'while(!isAcceptableColor($ color))',不是吗? – nibra 2013-04-10 16:26:18
我确定:)如果我没有把这个评论放在'isAcceptableColor'方法中,我可能会以“这取决于函数返回的内容”的借口离开了,但你得到了我。谢谢 – 2013-04-10 17:32:27
你为什么不只是使用一个颜色值的数组,并使用'array_rand()' – Oussama 2013-04-10 15:37:35
我对色彩理论并不是很好,但如果你只是担心色彩在H/S/L色彩空间中太亮/暗你只是把L值的上限和下限? – Sammitch 2013-04-10 16:06:39