随机函数仅返回一些可能的颜色
我有一个生成随机颜色的 php 函数,但我需要截断它,以便它只返回浅色(这样文本可以更容易地形成对比),我该怎么做?我很难用十六进制思考来进行比较。这是我的功能:
function randomColor() {
$str = '#';
for($i = 0 ; $i < 6 ; $i++) {
$randNum = rand(0 , 15);
switch ($randNum) {
case 10: $randNum = 'A'; break;
case 11: $randNum = 'B'; break;
case 12: $randNum = 'C'; break;
case 13: $randNum = 'D'; break;
case 14: $randNum = 'E'; break;
case 15: $randNum = 'F'; break;
}
$str .= $randNum;
}
return $str;
}
$color = randomColor();
I have a php function that generates a random color, but I need to truncate it so it only returns the light colors (so text can contrast more easily), how can I do this? I have trouble thinking it in Hex to make the comparisons. Here's my function:
function randomColor() {
$str = '#';
for($i = 0 ; $i < 6 ; $i++) {
$randNum = rand(0 , 15);
switch ($randNum) {
case 10: $randNum = 'A'; break;
case 11: $randNum = 'B'; break;
case 12: $randNum = 'C'; break;
case 13: $randNum = 'D'; break;
case 14: $randNum = 'E'; break;
case 15: $randNum = 'F'; break;
}
$str .= $randNum;
}
return $str;
}
$color = randomColor();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
浅色具有较高的十六进制值(#FFFFFF = 白色)。
最好以三份的形式生成颜色,而不是 6 个单独的部分,这样您就可以生成红色、绿色和蓝色分量。此外,您还可以使用
dechex()
将十进制转换为十六进制,并摆脱那个丑陋的switch
结构。您可以将
rand()
中的最小值设置为高于 0,以获得较浅的颜色,或者同样将最大值设置得较低以使其变暗。因此,您可以调用例如
randomColor(150,255)
来获得较浅的颜色,或调用randomColor(0,100)
来获得较深的颜色。Light colors have higher values in hex (#FFFFFF = white).
You would be much better generating the colours in threes, rather than 6 individual parts so you generate a red, green and blue component. Also, you can use
dechex()
to convert from decimal to hex and get rid of that uglyswitch
structure.You can just set a minimum value in your
rand()
higher than 0 for the lighter colors, or equally make the maximum lower to make it darker.So you can call e.g.
randomColor(150,255)
to get a lighter colour orrandomColor(0,100)
to get a darker colour.0xAA == 170 因此您可以选择 170 到 255 之间的随机数并将其转换为十六进制。
0xAA == 170 so you can pick a random number between 170 and 255 and convert it to hexadecimal.