【问题标题】:randomly generating colors with php用php随机生成颜色
【发布时间】:2013-04-02 13:21:42
【问题描述】:

所以我正在努力让我的标题每天都改变颜色,并且我试图使用随机颜色来创建它。标题中有 2 种颜色,我正在制作它们的互补色。第一种颜色是随机生成的,然后通过 150` 更改色调来修改第二种颜色。问题是选择某些颜色时,它们可能是过于振勃或黑色的。我正在运行一个检查,以便我可以稍微控制亮度值,但仍有一些颜色太亮(例如极黄色)。我将在下面发布我的代码。任何帮助或建议表示赞赏!谢谢!

// 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 ."%)";

这看起来很简单,我相信有更好的方法。我环顾四周,但我注意到的只是色调等的基本公式。再次感谢!

【问题讨论】:

  • 为什么不直接使用颜色值数组并使用array_rand()
  • 我不太擅长色彩理论,但如果你只是担心在 H/S/L 色彩空间中颜色太亮/太暗,你就不能把上部和L 值的下限?

标签: php colors


【解决方案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) );

【讨论】:

  • 我确定你的意思是while (!isAcceptableColor($color)),不是吗?
  • 我当然可以 :) 如果我没有在 isAcceptableColor 方法中添加该评论,我可能会以“这取决于函数返回的内容”为借口逃脱,但你得到了我。谢谢