Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A PHP Class to adjust a hex value (basicly mixing with another color)
<?php
namespace SayHello\nm;
/**
* This Class provides some color adjustments
*
* @author Nico Martin <nico@sayhello.ch>
*/
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
You can’t perform that action at this time.