Map value to color scale

后端 未结 5 779
执念已碎
执念已碎 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:40

    There might be libs to do that. However let's get a short warm up into the general principles. In general you have following options:

    1. A predefined color index, e.g. $coloridx=array(0=>'#FFFFFF',1=>'#FFEE00',...);
    2. Any algorithm, e.g. linear gradient, which is basically an iterations based adaption of all three RGB channels (R = red, G = green, B = blue).
    3. A combination of both, which usually puts the result of any complex algorithm to the color index and then goes from there.

    If you include algorithms in your considerations you must understand that there is no true or false. It all depends on what you would like to implement. There might be occasions where it makes sense to render variations of green into n=0..10 and then have red to black in everything beyond n>10. Caps and multipliers help to set accents. Things like that.

    One way of implementing a linear gradient would be:

    function lineargradient($ra,$ga,$ba,$rz,$gz,$bz,$iterationnr) {
      $colorindex = array();
      for($iterationc=1; $iterationc<=$iterationnr; $iterationc++) {
         $iterationdiff = $iterationnr-$iterationc;
         $colorindex[] = '#'.
            dechex(intval((($ra*$iterationc)+($rz*$iterationdiff))/$iterationnr)).
            dechex(intval((($ga*$iterationc)+($gz*$iterationdiff))/$iterationnr)).
            dechex(intval((($ba*$iterationc)+($bz*$iterationdiff))/$iterationnr));
      }
      return $colorindex;
    }
    
    $colorindex = lineargradient(
      100, 0, 0,   // rgb of the start color
      0, 255, 255, // rgb of the end color
      256          // number of colors in your linear gradient
    );
    
    $color = $colorindex[$value];
    

    I UPDATED the code to add dechex, which feeds back on the comments.

提交回复
热议问题