04.11.2020, 10:55
(04.11.2020, 07:48)admin Wrote: To dim a color your need to convert RGB to HSV, change V up/down and then convert back to RGB.Thank you very much! So my only doubt is which group addresses I need to define
Here are the functions that you can use.
Code:function rgbtohsv(r, g, b)
local max, min, d, h, s, v
max = math.max(r, g, b)
min = math.min(r, g, b)
d = max - min
s = max == 0 and 0 or (d / max)
v = max / 255
if max == min then
h = 0
elseif max == r then
h = (g - b) + d * (g < b and 6 or 0)
h = h / (6 * d)
elseif max == g then
h = (b - r) + d * 2
h = h / (6 * d)
elseif max == b then
h = (r - g) + d * 4
h = h / (6 * d)
end
return h, s, v
end
function hsvtorgb(h, s, v)
local r, g, b, i, f, p, q, t, z
i = math.floor(h * 6)
f = h * 6 - i
p = v * (1 - s)
q = v * (1 - f * s)
t = v * (1 - (1 - f) * s)
z = i % 6
if z == 0 then
r = v
g = t
b = p
elseif z == 1 then
r = q
g = v
b = p
elseif z == 2 then
r = p
g = v
b = t
elseif z == 3 then
r = p
g = q
b = v
elseif z == 4 then
r = t
g = p
b = v
elseif z == 5 then
r = v
g = p
b = q
end
r = math.round(r * 255)
g = math.round(g * 255)
b = math.round(b * 255)
return r, g, b
end
function rgbstep(r, g, b, up, step)
local h, s, v = rgbtohsv(r, g, b)
local v2 = up and math.min(1, v + step) or math.max(0, v - step)
if v == v2 then
return
end
return hsvtorgb(h, s, v2)
end
rgbstep(r, g, b, up, step) can perform up/down step of current RGB value.
arguments:rgbstep will return new RGB values but it might also return nil when further step is not possible.
- r, g, b - color components in 0..255 range
- up - true = step up / false = step down
- step - step size, V range is 0..1 so the step should be something like 0.1 or 0.05 depending on how many total steps you want
Code:-- values from split RGB value
r = 127
g = 255
b = 10
-- step down
up = false
-- maximum 20 steps between min and max
step = 0.05
r, g, b = rgbstep(r, g, b, up, step)
if r then
-- write new values
else
-- stop dimming
end