Grade Between Two Hex Colors

CSS colors gradation example

Yesterday I wanted to gradually shade between two hex colors. To perform artihmetic/math on hex colors in PHP you need to break them apart, turn them into decimals, change them back into hex and then put them back together.

Here’s what I came up with:

function hexColorToRgb($color) {
    return [hexdec(mb_substr($color, 0, 2)),
        hexdec(mb_substr($color, 2, 2)),
        hexdec(mb_substr($color, 4, 2))];
}

function colorGrade($p, $start, $end) {
    $start_rgb = hexColorToRgb($start);
    $end_rgb = hexColorToRgb($end);
    $rgb = [$start_rgb[0] * (1.0 - $p) + $end_rgb[0] * $p,
            $start_rgb[1] * (1.0 - $p) + $end_rgb[1] * $p,
            $start_rgb[2] * (1.0 - $p) + $end_rgb[2] * $p];
    return dechex($rgb[0]) . dechex($rgb[1]) . dechex($rgb[2]);
}

// Example:
$start_color = 'c4dbf5';
$end_color = '333333';
echo colorGrade(0.25, $start_color, $end_color); # 9fb1c4
echo colorGrade(0.5, $start_color, $end_color);  # 7b8794
echo colorGrade(0.75, $start_color, $end_color); # 575d63

Leave a Reply

Your email address will not be published.