use*_*562 35
感谢指点,这似乎做了一个称职的工作:
function stringToColorCode($str) {
$code = dechex(crc32($str));
$code = substr($code, 0, 6);
return $code;
}
$str = 'test123';
print '<span style="background-color:#'.stringToColorCode($str).'">'.$str.'</span>';
Run Code Online (Sandbox Code Playgroud)
sje*_*397 21
几乎总是,只使用随机颜色
我建议创建一个(长的)颜色列表,它们可以很好地与你的背景一起工作 - 然后用你的颜色数量散列字符串和模数(%)来得到表格的索引.
public function colorFromString($string)
{
$colors = [
'#0074D9',
'#7FDBFF',
'#39CCCC',
// this list should be as long as practical to avoid duplicates
];
// generate a partial hash of the string (a full hash is too long for the % operator)
$hash = substr(sha1($string), 0, 10);
// determine the color index
$colorIndex = hexdec($hash) % count($colors);
return $colors[$colorIndex];
}
Run Code Online (Sandbox Code Playgroud)
Rei*_*ien 17
我同意上面的sje397,完全随意的颜色可能最终看起来很讨厌.我建议选择恒定的饱和度+发光值,并根据内容改变色调,而不是制作一长串漂亮的颜色.要从HSL颜色获取RGB颜色,您可以使用类似于http://en.wikipedia.org/wiki/HSL_and_HSV#Converting_to_RGB中描述的颜色.
这是一个例子(在http://codepad.viper-7.com中尝试一些有用的东西,例如https://codepad.remoteinterview.io/ZXBMZWYJFO):
<?php
function hsl2rgb($H, $S, $V) {
$H *= 6;
$h = intval($H);
$H -= $h;
$V *= 255;
$m = $V*(1 - $S);
$x = $V*(1 - $S*(1-$H));
$y = $V*(1 - $S*$H);
$a = [[$V, $x, $m], [$y, $V, $m],
[$m, $V, $x], [$m, $y, $V],
[$x, $m, $V], [$V, $m, $y]][$h];
return sprintf("#%02X%02X%02X", $a[0], $a[1], $a[2]);
}
function hue($tstr) {
return unpack('L', hash('adler32', $tstr, true))[1];
}
$phrase = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
$words = [];
foreach (explode(' ', $phrase) as $word)
$words[hue($word)] = $word;
ksort($words);
foreach ($words as $h => $word) {
$col = hsl2rgb($h/0xFFFFFFFF, 0.4, 1);
printf('<span style="color:%s">%s</span> ', $col, $word);
}
?>
Run Code Online (Sandbox Code Playgroud)