diff --git a/README.md b/README.md index 1520c1c..1080c9f 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,7 @@ Here's a complete list of the `Color` methods available in templates: - `Blue` returns the blue color component - `CSSColor` returns the color as `rgba`. The alpha value can be specified with the (optional) argument. - `Luminance` the luminance of the color as a floating-point value ranging from 0-1 + - `Blend` blends the color with a second background color (defaults to #FFFFFF) with the given opacity. `$BGColor.Blend(0.5, '#000000')` will give the color 50% opacity and put it on top of a black background. - `AlteredColorHSV` modifies the current color by the given HSV values. These values are offsets, so you could do something like this: `$BgColor.AlteredColorHSV(0.5, 0, 0)` which will return the color with the opposite hue. All parameters are percentage based and range from `0 - 1`. So doing: `$BgColor.AlteredColorHSV(0, 0, -0.2)` will result in a color with 20% less brightness (absolute, not relative). diff --git a/code/Color.php b/code/Color.php index 5d79407..ad94554 100644 --- a/code/Color.php +++ b/code/Color.php @@ -215,6 +215,31 @@ public function AlteredColorHSV($hChange, $sChange, $vChange){ return $color; } + /** + * Blend the color with a background color, with the given opacity level + * @param float $opacity Opacity level of the current color (between 0 - 1) + * @param string $background The background color + * @return string + */ + public function Blend($opacity, $background = 'FFFFFF') { + list($R, $G, $B) = self::HEX_TO_RGB($this->value); + list($bgR, $bgG, $bgB) = self::HEX_TO_RGB(ltrim($background, '#')); + $opacity = self::clamp($opacity, 0, 1); + + $add = array( + 'r' => ($bgR - $R) / 100, + 'g' => ($bgG - $G) / 100, + 'b' => ($bgB - $B) / 100 + ); + + $transparency = (1 - $opacity) * 100; + $R += intval($add['r'] * $transparency); + $G += intval($add['g'] * $transparency); + $B += intval($add['b'] * $transparency); + + return self::RGB_TO_HEX($R, $G, $B); + } + private static function clamp($val, $min, $max){ return min($max, max($min, $val)); }