Merge pull request #14128 from agileware/CIVICRM-1143
[civicrm-core.git] / CRM / Utils / Color.php
index 5d965dd342e6371c5a411c3ae76594c5d4a0a2ca..2cceca9ff33468d6027255e2f5361fa96bfc96fc 100644 (file)
@@ -3,7 +3,7 @@
  +--------------------------------------------------------------------+
  | CiviCRM version 5                                                  |
  +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2018                                |
+ | Copyright CiviCRM LLC (c) 2004-2019                                |
  +--------------------------------------------------------------------+
  | This file is a part of CiviCRM.                                    |
  |                                                                    |
@@ -28,7 +28,7 @@
 /**
  *
  * @package CRM
- * @copyright CiviCRM LLC (c) 2004-2018
+ * @copyright CiviCRM LLC (c) 2004-2019
  */
 
 /**
@@ -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));
   }
 
 }