Created
April 2, 2020 19:53
-
-
Save alexmustin/a5e468298bad535f64ae32100c2e8262 to your computer and use it in GitHub Desktop.
Snippet - function to Increase/Decrease brightness of a HEX color by a percentage
This file contains hidden or 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 | |
| /** | |
| * Increases or decreases the brightness of a color by a percentage of the current brightness. | |
| * | |
| * Credit: https://stackoverflow.com/a/54393956/4256497 | |
| * | |
| * @param string $hex_code Supported formats: `#FFF`, `#FFFFFF`, `FFF`, `FFFFFF` | |
| * @param float $adjust_pct A number between -1 and 1. E.g. 0.3 = 30% lighter; -0.4 = 40% darker. | |
| * | |
| * @return string | |
| */ | |
| function adjust_brightness( $hex_code, $adjust_pct ) { | |
| $hex_code = ltrim( $hex_code, '#' ); | |
| if ( strlen( $hex_code ) === 3 ) { | |
| $hex_code = $hex_code[0] . $hex_code[0] . $hex_code[1] . $hex_code[1] . $hex_code[2] . $hex_code[2]; | |
| } | |
| $hex_code = array_map( 'hexdec', str_split( $hex_code, 2 ) ); | |
| foreach ( $hex_code as & $color ) { | |
| $adjustable_limit = $adjust_pct < 0 ? $color : 255 - $color; | |
| $adjust_amount = ceil( $adjustable_limit * $adjust_pct ); | |
| $color = str_pad( dechex( $color + $adjust_amount ), 2, '0', STR_PAD_LEFT ); | |
| } | |
| return '#' . implode( $hex_code ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment