Dunno what to call this…

I’ve been searching for a way to get the color between two colours based on only a percentage. I’ve never been great with graphics / colours e.t.c.

But this script below is a modified version of this script, where you can easily create your own gradients. As I didn’t create the original script, all fame go to the author Andrew Pociu.

<?php

function PercentColor($Percent, $HexMin = NULL, $HexMax = NULL) {
    $maxPercent = 100;
    $HexMin = $HexMin ? $HexMin : "000000"; // Set own default colour here.
    $HexMax = $HexMax ? $HexMax : "FFFFFF"; // Set own default colour here.

    $FromRGB['r'] = hexdec(substr($HexMin, 0, 2));
    $FromRGB['g'] = hexdec(substr($HexMin, 2, 2));
    $FromRGB['b'] = hexdec(substr($HexMin, 4, 2));

    $ToRGB['r'] = hexdec(substr($HexMax, 0, 2));
    $ToRGB['g'] = hexdec(substr($HexMax, 2, 2));
    $ToRGB['b'] = hexdec(substr($HexMax, 4, 2));

    $StepRGB['r'] = ($FromRGB['r'] - $ToRGB['r']) / ($maxPercent);
    $StepRGB['g'] = ($FromRGB['g'] - $ToRGB['g']) / ($maxPercent);
    $StepRGB['b'] = ($FromRGB['b'] - $ToRGB['b']) / ($maxPercent);

    $RGB['r'] = floor($FromRGB['r'] - ($StepRGB['r'] * $Percent));
    $RGB['g'] = floor($FromRGB['g'] - ($StepRGB['g'] * $Percent));
    $RGB['b'] = floor($FromRGB['b'] - ($StepRGB['b'] * $Percent));

    $HexRGB['r'] = sprintf('%02x', ($RGB['r']));
    $HexRGB['g'] = sprintf('%02x', ($RGB['g']));
    $HexRGB['b'] = sprintf('%02x', ($RGB['b']));

    $GradientColors[] = implode(NULL, $HexRGB);

    return implode(NULL, $HexRGB);
}

for($i = 0; $i < 100; $i++) {
    echo "<div style=\"background-color: #" . PercentColor($i, "20DD20", "DD2020") . "; width: 100px; height: 10px;\"></div>";
}
?>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s