Skip to content

Instantly share code, notes, and snippets.

@xwiz
Last active August 15, 2021 11:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xwiz/6e35fbfd76092f92a164a66e230ab8f9 to your computer and use it in GitHub Desktop.
Save xwiz/6e35fbfd76092f92a164a66e230ab8f9 to your computer and use it in GitHub Desktop.
Random gradient color by weight
/**
* @param mixed $color1 The first hex/rgb array gradient color
* @param mixed $color2 The second hex/rgb array gradient color
* @param mixed $weight Weight of color 1 against color 2. Should be a float between 0 and 1
* @return string A hex color mix of the two gradient colors based on weight
*/
function pick_hex($color1, $color2, $weight) {
$w1 = $weight;
$w2 = 1 - $w1;
if (is_string($color1)) {
list($r1, $g1, $b1) = sscanf($color1, "#%02x%02x%02x");
} elseif (is_array($color1)) {
$r1 = $color1[0]; $g1 = $color1[1]; $b1 = $color1[2];
}
if (is_string($color2)) {
list($r2, $g2, $b2) = sscanf($color2, "#%02x%02x%02x");
} elseif (is_array($color2)) {
$r2 = $color2[0]; $g2 = $color2[1]; $b2 = $color2[2];
}
$rgb = [round($r1 * $w1 + $r2 * $w2),
round($g1 * $w1 + $g2 * $w2),
round($b1 * $w1 + $b2 * $w2)];
return sprintf("#%02x%02x%02x", $rgb[0], $rgb[1], $rgb[2]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment