Gradient

Introduction
Our eyes can process graphical data much faster then numerical. The following two functions allow you to convert numerical data into a hexadecimal colorgradient given three variables {min, val, max} with the relation: min <= val <= max. The actual color gradient looks like this:

Gradient
The following function converts a value between min, max into a hexadecimal color. function gradient(min, max, val) if (val > max) then val = max end if (val < min) then val = min end

local v = val - min local d = (max - min) * 0.5 local red, green

if (v <= d) then red = (255 * v) / d   green = 255 else red = 255 green = 255 - (255 * (v-d)) / (max - min - d) end

return string.format("#%02x%02x00", red, green) end

Example
The following example shows my cores temperature and usage in a color gradient using Wicked. --

Gradient2
The following function is not limited to a gradient from green to red. It works the same way as the original gradient, but you can specify your own start color and stop color.

function gradient(color, to_color, min, max, value) local function color2dec(c) return tonumber(c:sub(2,3),16), tonumber(c:sub(4,5),16), tonumber(c:sub(6,7),16) end

local factor = 0 if (value >= max ) then factor = 1 elseif (value > min ) then factor = (value - min) / (max - min) end

local red, green, blue = color2dec(color) local to_red, to_green, to_blue = color2dec(to_color)

red  = red   + (factor * (to_red   - red)) green = green + (factor * (to_green - green)) blue = blue  + (factor * (to_blue  - blue))

-- dec2color return string.format("#%02x%02x%02x", red, green, blue) end

Example
Here we calculate in the interactive lua interpreter the color in the middle of white and black. (which is obvious grey) > = print(gradient("#000000","#ffffff",0,100,50))
 * 1) 7f7f7f

This is a sophisticated example for vicious. It shows all your cpu cores in the form cpu1%/cpu2%/cpuX%. If the usage of one core rise above 50%, the gradient function begin to highlight it. The chosen color are optimised for the default theme. Adapt it to your needs. local cpuwidget = widget({ type = "textbox" })

vicious.register(cpuwidget, vicious.widgets.cpu, function (widget, args) local text  -- list only real cpu cores  for i=1,#args do    -- alerts, if system is stressed    if args[i] > 50 then      -- from light green to light red      local color = gradient("#AECF96","#FF5656",50,100,args[i])      args[i] = string.format(" %s ", color, args[i])    end

-- append to list if i > 2 then text = text.."/"..args[i].."%" else text = args[i].."%" end end

return text end )