Last active
August 29, 2015 13:57
-
-
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"
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 | |
/** | |
* 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