Last active
June 30, 2017 07:19
-
-
Save nico-martin/0ddd5b6ce6a2915c88a2a64d2c56180e to your computer and use it in GitHub Desktop.
A PHP Class to adjust a hex value (basicly mixing with another color)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace SayHello\nm; | |
/** | |
* This Class provides some color adjustments | |
* | |
* @author Nico Martin <[email protected]> | |
*/ | |
class Color_Adjustments { | |
public $color = []; | |
public function __construct( $hex ) { | |
$this->color = $this->hex2rgb( $hex ); | |
} | |
/** | |
* @param string $hex | |
*/ | |
public function hex2rgb( $hex = '#000000' ) { | |
$f = function( $x ) { | |
return hexdec( $x ); | |
}; | |
return array_map( $f, str_split( str_replace( '#', '', $hex ), 2 ) ); | |
} | |
/** | |
* @param array $rgb | |
* | |
* @return string | |
*/ | |
public function rgb2hex( $rgb = [ 0, 0, 0 ] ) { | |
$f = function( $x ) { | |
return str_pad( dechex( $x ), 2, '0', STR_PAD_LEFT ); | |
}; | |
return '#' . implode( '', array_map( $f, $rgb ) ); | |
} | |
/** | |
* @return mixed | |
*/ | |
public function get_hex () { | |
return $this->rgb2hex( $this->color ); | |
} | |
/** | |
* Color adjustments | |
*/ | |
/** | |
* @param array $color_2 | |
* @param float $weight | |
*/ | |
public function mix( $color_2 = [ 0, 0, 0 ], $weight = 0.5 ) { | |
if ( is_string( $color_2 ) ) { | |
$color_2 = $this->hex2rgb( $color_2 ); | |
} | |
$f = function( $x ) use ( $weight ) { | |
return $weight * $x; | |
}; | |
$g = function( $x ) use ( $weight ) { | |
return (1 - $weight) * $x; | |
}; | |
$h = function( $x, $y ) { | |
return round( $x + $y ); | |
}; | |
$this->color = array_map( $h, array_map( $f, $this->color ), array_map( $g, $color_2 ) ); | |
} | |
/** | |
* @param float $weight | |
*/ | |
public function tint( $weight = 0.5 ) { | |
$this->color = $this->mix( $this->color, [ 255, 255, 255 ], $weight ); | |
} | |
/** | |
* @param float $weight | |
*/ | |
public function tone( $weight = 0.5 ) { | |
$this->color = $this->mix( $this->color, [ 128, 128, 128 ], $weight ); | |
} | |
/** | |
* @param float $weight | |
*/ | |
public function shade( $weight = 0.5 ) { | |
$this->color = $this->mix( $this->color, [ 0, 0, 0 ], $weight ); | |
} | |
} | |
$color = new Color_Adjustments( '#ff0000' ); | |
$color->mix( '#0000ff' ); | |
echo $color->get_hex(); // #800080 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment