Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

php - Color coding based on number

I want to display a color between red, yellow, green depending on a number between 1 to 100.

1 being green and 100 being red, 50 being yellow. I want to basically create a gradient between that.

So far, I tried:

$r = floor(255 * ($number / 100));
$g = 255 - $r;

And it somewhat does it, but gives me brownish & dark colors, & no yellow at all.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's because you shouldn't change both channels at once but rise R in the first half and lower G in the second.

Try a function like this:

function GreenYellowRed($number) {
  $number--; // working with 0-99 will be easier

  if ($number < 50) {
    // green to yellow
    $r = floor(255 * ($number / 50));
    $g = 255;

  } else {
    // yellow to red
    $r = 255;
    $g = floor(255 * ((50-$number%50) / 50));
  }
  $b = 0;

  return "$r,$g,$b";
}

To test it:

$output = "";
for ($i = 1; $i <= 100; $i++) {
  $rgb = GreenYellowRed($i);
  $output .= "<div style='background-color: rgb($rgb)'>$rgb</div>";
}
echo $output;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...