Search code examples
pythoncolorsrgbrgba

I need a function to return RGBA values based on a variable


I have a variabble ranging from -10 to 10 and constantly changing. I want to have a python function returning RGBA values:

Red: when close to -10,
Green: when close to 10

I can't think of a way to do this myself and I suppose someone has done something like that in the past.


Solution

  • You can use a color representation like HSV to do this. You can take your rgb color max (255, 0, 0) and min (0, 255, 0) and convert those to HSV (0, 100%, 100%) (120, 100%, 100%). Looking at these you can see that only one value changes, the hue. So you can map your range -10:10 to the range of the hue 0:120. This can be done using a pretty simple mapping function:

    def map_values(oldValue):
        # this is your range -10:10
        OldRange = (10 - -10)
        # range we are mapping to 0:120
        NewRange = (120 - 0)
        return (((oldValue - -10) * NewRange) / OldRange) + 0
    

    Now that you have a hue, you can convert that into an RGB value. There is a handy function for this in colorsys

    import colorsys
    # we need to divide by 360 because this function
    # expects a value from 0.0 to 1.0. H has a range from 0 to 360
    my_rgb_color = colorsys.hsv_to_rgb(map_values(your_value) / 360.0, 1.0, 1.0)