X-Git-Url: https://vcs.fsf.org/?a=blobdiff_plain;f=CRM%2FUtils%2FColor.php;h=2cceca9ff33468d6027255e2f5361fa96bfc96fc;hb=850d8c7cf555cdb11176418b2d1ecd035eddcb14;hp=80bac7f8f898dfe7fccda91c2f401549b1b14a3a;hpb=6fe426fc1c924bbfcf29735d5f9e9763b1dbd389;p=civicrm-core.git diff --git a/CRM/Utils/Color.php b/CRM/Utils/Color.php index 80bac7f8f8..2cceca9ff3 100644 --- a/CRM/Utils/Color.php +++ b/CRM/Utils/Color.php @@ -42,15 +42,55 @@ class CRM_Utils_Color { * Based on YIQ value. * * @param string $hexcolor + * @param string $black + * @param string $white * @return string */ - public static function getContrast($hexcolor) { - $hexcolor = trim($hexcolor, ' #'); - $r = hexdec(substr($hexcolor, 0, 2)); - $g = hexdec(substr($hexcolor, 2, 2)); - $b = hexdec(substr($hexcolor, 4, 2)); + public static function getContrast($hexcolor, $black = 'black', $white = 'white') { + list($r, $g, $b) = self::getRgb($hexcolor); $yiq = (($r * 299) + ($g * 587) + ($b * 114)) / 1000; - return ($yiq >= 128) ? 'black' : 'white'; + return ($yiq >= 128) ? $black : $white; + } + + /** + * Convert hex color to decimal + * + * @param string $hexcolor + * @return array + * [red, green, blue] + */ + public static function getRgb($hexcolor) { + $hexcolor = trim($hexcolor, ' #'); + if (strlen($hexcolor) === 3) { + $hexcolor = $hexcolor[0] . $hexcolor[0] . $hexcolor[1] . $hexcolor[1] . $hexcolor[2] . $hexcolor[2]; + } + return [ + hexdec(substr($hexcolor, 0, 2)), + hexdec(substr($hexcolor, 2, 2)), + hexdec(substr($hexcolor, 4, 2)), + ]; + } + + /** + * Calculate a highlight color from a base color + * + * @param $hexcolor + * @return string + */ + public static function getHighlight($hexcolor) { + $rgb = CRM_Utils_Color::getRgb($hexcolor); + $avg = array_sum($rgb) / 3; + foreach ($rgb as &$v) { + if ($avg > 242) { + // For very bright values, lower the brightness + $v -= 50; + } + else { + // Bump up brightness on a nonlinear curve - darker colors get more of a boost + $v = min(255, intval((-.0035 * ($v - 242) ** 2) + 260)); + } + } + return '#' . implode(array_map('dechex', $rgb)); } }