使用PHP随机生成颜色 [英] Random color generation using PHP

查看:270
本文介绍了使用PHP随机生成颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在PHP中生成随机HTML颜色,但我无法让他们看起来相似,或在同一个家庭。是否有一些函数我可以用来生成的颜色是类似另一种颜色,除了生成和连接6个随机的十六进制数字?

I'm trying to generate random HTML colors in PHP, but I'm having trouble getting them to look similar, or in the same family. Is there some function I can use to generate colors that are "similar" to another color, besides just generating and concatenating 6 random hex digits?

推荐答案

您可以


  1. 在25和230之间生成一个随机十进制数(您的基本数字)

  2. 生成1到25之间的3个随机数(任意决定它们是正数还是负数)

  3. 将这三个数字添加到基数中, R,G和B)

  4. 重复步骤2和3获得更多类似的颜色

  1. Generate one random decimal number betweem 25 and 230 (your "base" number)
  2. Generate 3 random numbers between 1 and 25 (arbitrarily deciding whether they will be positive or negative)
  3. Add those three numbers to your base number to get three different numbers (your R, G, and B)
  4. Repeat steps 2 and 3 to get more, similar colors

您可以加宽修饰符号的范围(从1到25),以获得更多的颜色差异(您还必须更改基本数字的范围,因此您可以保持在0和255之间) 。

You could widen the range of the modifier number (the one from 1 to 25) to get more variance in your color (you'd have to change the range of your base number as well, so you stay between 0 and 255).

我不知道PHP的什么,这就是为什么我不放代码。但我认为这是一个有趣的问题=)

I don't know anything about PHP, which is why I'm not putting code. But I thought it was an interesting question =)

编辑:我意识到在第1步生成3个随机基数会让你少静音看(灰色)颜色。然后你可以按照步骤2和3得到不同的色调等,正如我已经提到的(和@Peter提到,增加修饰符号的风险是获得较少的相似的颜色)

I realized that generating 3 random base numbers in step 1 will get you a less muted looking (grey) color. Then you can follow steps 2 and 3 to get different shades etc. as I already mentioned (and, as @Peter mentioned, increasing the modifier number at the risk of getting less "similar" colors)

此技术的输出示例基于两组不同的基数):

这里是@Peter Ajtai的PHP实现

EDIT 2: Here is the PHP implementation of this by @Peter Ajtai

<?php
$spread = 25;
for ($row = 0; $row < 100; ++$row) {
        for($c=0;$c<3;++$c) {
        $color[$c] = rand(0+$spread,255-$spread);
    }
    echo "<div style='float:left; background-color:rgb($color[0],$color[1],$color[2]);'>&nbsp;Base Color&nbsp;</div><br/>";
    for($i=0;$i<92;++$i) {
    $r = rand($color[0]-$spread, $color[0]+$spread);
    $g = rand($color[1]-$spread, $color[1]+$spread);
    $b = rand($color[2]-$spread, $color[2]+$spread);    
    echo "<div style='background-color:rgb($r,$g,$b); width:10px; height:10px; float:left;'></div>";
    }    
    echo "<br/>";
}
?>

这篇关于使用PHP随机生成颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆