有了這個功能,你可以在十六進制格式創建顏色的深或淺的色調:
/**
* string $code Color in hex format, e.g. '#ff0000'
* int $percentage A number between 0 and 1, e.g. 0.3
* 1 is the maximum amount for the shade, and thus means black
* or white depending on the parameter $darken.
* 0 returns the color in $code itself.
* boolean $darken True if the function should return a dark shade of $code
* or false if the function should return a light shade of $code.
*/
function colorCodeShade($code, $percentage, $darken=true) {
// split color code in its rgb parts and convert these into decimal numbers
$r = hexdec(substr($code, 1, 2));
$g = hexdec(substr($code, 3, 2));
$b = hexdec(substr($code, 5, 2));
if($darken) {
$newR = dechex($r * (1 - $percentage));
$newG = dechex($g * (1 - $percentage));
$newB = dechex($b * (1 - $percentage));
} else {
$newR = dechex($r + (255 - $r) * $percentage);
$newG = dechex($g + (255 - $g) * $percentage);
$newB = dechex($b + (255 - $b) * $percentage);
}
if(strlen($newR) == 1) $newR = '0'.$newR;
if(strlen($newG) == 1) $newG = '0'.$newG;
if(strlen($newB) == 1) $newB = '0'.$newB;
return '#'.$newR.$newG.$newB;
}
echo '<span style="color:'.colorCodeShade('#204a96', 0.5, true).'">test</span>';
echo '<span style="color:'.colorCodeShade('#204a96', 0.5, false).'">test</span>';