Generator::color_luminance( string $hex, float $percent )

Description #

Lightens/darkens a given colour (hex format), returning the altered colour in hex format.

Parameters #

  • $hex
    string (Required) Colour as hexadecimal (with or without hash).
  • $percent
    float (Required) float $percent Decimal ( 0.2 = lighten by 20%(), -0.4 = darken by 40%() ).

Source #

File: addons/avatar/class-generator.php

	private function color_luminance( $hex, $percent ) {
		// Validate hex string.
		$hex     = preg_replace( '/[^0-9a-f]/i', '', $hex );
		$new_hex = '#';

		if ( strlen( $hex ) < 6 ) {
			$hex = $hex[0] + $hex[0] + $hex[1] + $hex[1] + $hex[2] + $hex[2];
		}

		// Convert to decimal and change luminosity.
		for ( $i = 0; $i < 3; $i++ ) {
			$dec      = hexdec( substr( $hex, $i * 2, 2 ) );
			$dec      = min( max( 0, $dec + $dec * $percent ), 255 );
			$new_hex .= str_pad( dechex( $dec ), 2, 0, STR_PAD_LEFT );
		}

		return $new_hex;
	}

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Add your comment