Map value to color scale

后端 未结 5 771
执念已碎
执念已碎 2021-01-18 11:13

I have a list of values which should be plotted to a map with a certain color. The plotting to the map is already done, but I need to figure out a way to map the value

5条回答
  •  粉色の甜心
    2021-01-18 11:23

    Colors values are representations. Numeric colors as well as hexadecimal colors. A "not grayscale" color contains at least 2 different informations: Red value, green value or blue values may be different. Performing operation on its representation gives wrong result. The 'Mapping" must then be performed on each pieces of information. You need to extract red, green and blue values, perform the mapping seperatly, then build the representation of the result color. Here is a quick helper that use a "min color" and "max color", performs mapping on red, green and blue values, according to the "n" value you need to work with, then return the result color in hexadecimal string. It works for any colors or gray scale color as well.

    function linear_color($from, $to, $ratio) {
            // normalize ralio
            $ratio = $ratio<0?0:($ratio>1?1:$ratio);
            // unsure colors are numeric values
            if(!is_numeric($from))$from=hexdec($from);
            if(!is_numeric($to))$to=hexdec($to);
    
            $rf = 0xFF & ($from >> 0x10);
            $gf = 0xFF & ($from >> 0x8);
            $bf = 0xFF & $from;
            $rt = 0xFF & ($to >> 0x10);
            $gt = 0xFF & ($to >> 0x8);
            $bt = 0xFF & $to;
            return str_pad( dechex(($bf + (($bt-$bf)*$ratio)) + ($gf + (($gt-$gf)*$ratio) << 0x8) + ($rf + (($rt-$rf)*$ratio) << 0x10)), 6,'0',STR_PAD_LEFT);
    }
    

    Just specify 2 colors as numeric value or hexadecimal string (without hash!) like this :

    $color_from = hexdec('c2c2c2');
    $color_to = hexdec('1eb02b');
    for($i=-0.2; $i<=1.3; $i+=0.04){
            echo '
    '; echo 'Result color when n = '.$i.''; echo '
    '; }

提交回复
热议问题