3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * Static utility functions for working with colors
21 class CRM_Utils_Color
{
23 const COLOR_FILE
= '[civicrm.root]/bower_components/css-color-names/css-color-names.json';
26 * Determine the appropriate text color for a given background.
30 * @param string $color
31 * @param string $black
32 * @param string $white
35 public static function getContrast($color, $black = 'black', $white = 'white') {
36 list($r, $g, $b) = self
::getRgb($color);
37 $yiq = (($r * 299) +
($g * 587) +
($b * 114)) / 1000;
38 return ($yiq >= 128) ?
$black : $white;
42 * Parse any color string into rgb decimal values
48 * RGB notation: "rgb(255, 255, 255)"
50 * @param string $color
54 public static function getRgb($color) {
55 $color = str_replace(' ', '', $color);
56 $color = self
::nameToHex($color) ??
$color;
57 if (strpos($color, 'rgb(') === 0) {
58 return explode(',', substr($color, 4, strpos($color, ')') - 4));
60 $color = ltrim($color, '#');
61 if (strlen($color) === 3) {
62 $color = $color[0] . $color[0] . $color[1] . $color[1] . $color[2] . $color[2];
64 if (!CRM_Utils_Rule
::color('#' . $color)) {
68 hexdec(substr($color, 0, 2)),
69 hexdec(substr($color, 2, 2)),
70 hexdec(substr($color, 4, 2)),
75 * Calculate a highlight color from a base color
80 public static function getHighlight($color) {
81 $rgb = self
::getRgb($color);
82 $avg = array_sum($rgb) / 3;
83 foreach ($rgb as &$v) {
85 // For very bright values, lower the brightness
89 // Bump up brightness on a nonlinear curve - darker colors get more of a boost
90 $v = min(255, intval((-.0035 * ($v - 242) ** 2) +
260));
93 return self
::rgbToHex($rgb);
97 * Convert named color (e.g. springgreen) to hex
100 * @return string|null
102 public static function nameToHex($colorName) {
103 if (strpos($colorName, '#') !== FALSE ||
strpos($colorName, '(') !== FALSE) {
106 if (empty(Civi
::$statics[__CLASS__
]['names'])) {
107 Civi
::$statics[__CLASS__
]['names'] = json_decode(file_get_contents(Civi
::paths()->getPath(self
::COLOR_FILE
)), TRUE);
109 return Civi
::$statics[__CLASS__
]['names'][strtolower($colorName)] ??
NULL;
113 * Converts rgb array to hex string
118 public static function rgbToHex($rgb) {
120 foreach ($rgb as $dec) {
121 $ret .= str_pad(dechex($dec), 2, '0', STR_PAD_LEFT
);
127 * Validate color input and convert it to standard hex notation
129 * @param string $color
132 public static function normalize(&$color) {
133 $rgb = self
::getRgb($color);
135 $color = self
::rgbToHex($rgb);