简体   繁体   English

从数值中获取颜色值

[英]Get color value from numeric values

I need for a projet to get a color from a value.我需要一个项目来从一个值中获取颜色。 I explain, I have datas and each data must be represented by a color.我解释一下,我有数据,每个数据都必须用一种颜色表示。

The red color is for the maximum, and the blue for the minimum and the green is for the middle value.红色代表最大值,蓝色代表最小值,绿色代表中间值。 A kind of heatmap.一种热图。

So, I need to have a function returning the right color.所以,我需要一个 function 返回正确的颜色。

I tried something like this:我试过这样的事情:

    function datatocolor($min, $max, $value)
    {
        $half = (($min + $max) / 2);

        if ($value > $half)
        {
            $r = (255 * ($value+$min-$half)) / $half;
            $g = 255 - $r;
            $b = 0;
        } 
        else {
            $b = (255 * ($half-$value+$min)) / $half;
            $g = 255 - $b;
            $r = 0;         
        }
        $color = array(intval($r), intval($g),  intval($b));
        return $color;
    }

But, I get red and blue, and never green... I tried a lot of operations, I must be stupid but I don't find the right operation... Thanks in advance for your help !但是,我得到红色和蓝色,从来没有绿色......我尝试了很多操作,我一定很愚蠢但我没有找到合适的操作......提前感谢您的帮助!

I'm not a php expert, but as far as I can tell, the problem isn't with this code block.我不是 php 专家,但据我所知,问题不在于这个代码块。 I tested your algorithm in java just to be sure, and it looks to be correct:为了确定,我在 java 中测试了你的算法,它看起来是正确的:

public static void main(String[] args) {
    int min = 0;
    int max = 10;
    int half = (min + max) / 2;

    int r, g, b;

    // Cycling through the values for completeness' sake.
    for (int value = 0; value <= 10; value++) {
        if (value > half) {
        r = (255 * (value + min - half)) / half;
        g = 255 - r;
        b = 0;
    } else {
        b = (255 * (half - value + min)) / half;
        g = 255 - b;
        r = 0;
    }
    System.out.println("Value: " + value + " - " + new Color(r, g, b));
}

The output from this is what you would expect -- pure blue at minimum, pure green at the middle, and pure red at the maximum: output 就是你所期望的——至少是纯蓝色,中间是纯绿色,最大是纯红色:

Value: 0 - java.awt.Color[r=0,g=0,b=255]
Value: 1 - java.awt.Color[r=0,g=51,b=204]
Value: 2 - java.awt.Color[r=0,g=102,b=153]
Value: 3 - java.awt.Color[r=0,g=153,b=102]
Value: 4 - java.awt.Color[r=0,g=204,b=51]
Value: 5 - java.awt.Color[r=0,g=255,b=0]
Value: 6 - java.awt.Color[r=51,g=204,b=0]
Value: 7 - java.awt.Color[r=102,g=153,b=0]
Value: 8 - java.awt.Color[r=153,g=102,b=0]
Value: 9 - java.awt.Color[r=204,g=51,b=0]
Value: 10 - java.awt.Color[r=255,g=0,b=0]

Based on what you've provided, the problem seems to be either in the way you're calling the function, or in the way you're using the array it returns.根据您提供的内容,问题似乎出在您调用function 的方式上,或者出在您使用它返回的数组的方式上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM