按照 Frxstrem 给出的示例按百分比调整颜色并不理想。
如果您的颜色是黑色(RGB 中的 0,0,0),您将乘以零,这根本不会产生任何变化。如果您的颜色是深灰色(例如 RGB 中的 2,2,2),则必须将颜色调亮 50% 才能向上移动到 (3,3,3)。另一方面,如果您的 RGB 颜色为 (100,100,100),则调整 50% 会将您移至 (150,150,150),相比之下这是一个更大的变化。
更好的解决方案是按步长/数字 (0-255) 而不是按百分比进行调整,例如像这样(PHP 代码):
编辑 2014-01-06:稍微清理一下代码。
function adjustBrightness($hex, $steps) {
// Steps should be between -255 and 255. Negative = darker, positive = lighter
$steps = max(-255, min(255, $steps));
// Normalize into a six character long hex string
$hex = str_replace('#', '', $hex);
if (strlen($hex) == 3) {
$hex = str_repeat(substr($hex,0,1), 2).str_repeat(substr($hex,1,1), 2).str_repeat(substr($hex,2,1), 2);
}
// Split into three parts: R, G and B
$color_parts = str_split($hex, 2);
$return = '#';
foreach ($color_parts as $color) {
$color = hexdec($color); // Convert to decimal
$color = max(0,min(255,$color + $steps)); // Adjust color
$return .= str_pad(dechex($color), 2, '0', STR_PAD_LEFT); // Make two char hex code
}
return $return;
}