Skip to content

Instantly share code, notes, and snippets.

@GhostToast
Last active August 29, 2015 13:57
Show Gist options
  • Save GhostToast/9518787 to your computer and use it in GitHub Desktop.
Save GhostToast/9518787 to your computer and use it in GitHub Desktop.
Change a hex value by a positive or negative percentage, whether it is 3 or 6 characters in length. Percentage based on max (255), not self. So 100% will always be "#FFFFFF", -100% will always be "#000000"
<?php
/**
* Tint hex color by a percentage
*
* @param string $hex - #FFFFFF or #FFF
* @param int $percentage - Positive or negative
*
* @return string Returns modified $hex, lighter or darker
*/
function hex_tint( $hex, $percentage=0 ) {
if ( empty( $hex ) || 0 == $percentage || ! is_int( $percentage ) ) {
return $hex;
}
if ( '#' == substr( $hex, 0, 1 ) ) {
$temp_hex = trim( $hex, '#' );
$trimmed = true;
} else {
$temp_hex = $hex;
$trimmed = false;
}
if ( 3 == strlen( $temp_hex ) ) {
$temp_rgb = str_split( $temp_hex, 1 );
$rgb = array(
$temp_rgb[0],
$temp_rgb[0],
$temp_rgb[1],
$temp_rgb[1],
$temp_rgb[2],
$temp_rgb[2],
);
$rgb = str_split( implode( $rgb ), 2 );
} elseif ( 6 == strlen( $temp_hex ) ) {
$rgb = str_split( $temp_hex, 2 );
} else {
return $hex;
}
foreach ( $rgb as $key => $value ) {
$value = hexdec( $value );
$value = str_pad( dechex( max( min( ( ( ( $percentage / 100 ) * 255 ) + $value ), 255 ), 0 ) ), 2, '0', STR_PAD_LEFT );
$rgb[$key] = $value;
}
$hex = ( $trimmed ? '#' : '' ).implode( $rgb );
return $hex;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment