从数值获取颜色值 [英] Get color value from numeric values

查看:174
本文介绍了从数值获取颜色值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个projet从一个值获得一个颜色。
我解释,我有数据和每个数据必须用颜色表示。

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 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 !

推荐答案

我不是一个php专家,但据我所知,问题不在于这个代码块。我测试你的算法在java只是确定,它看起来是正确的:

I'm not a php expert, but as far as I can tell, the problem isn't with this code block. I tested your algorithm in java just to be sure, and it looks to be correct:

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:

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.

这篇关于从数值获取颜色值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆