Added function lume.color() and tests

This commit is contained in:
rxi 2015-05-09 15:12:52 +01:00
parent 9b48d704d2
commit a753f6e9a2
2 changed files with 39 additions and 0 deletions

View File

@ -682,6 +682,28 @@ function lume.ripairs(t)
end
function lume.color(str, mul)
mul = mul or 1
local r, g, b, a
r, g, b = str:match("#(%x%x)(%x%x)(%x%x)")
if r then
r = tonumber(r, 16) / 0xff
g = tonumber(g, 16) / 0xff
b = tonumber(b, 16) / 0xff
a = 1
elseif str:match("rgba?%s*%([%d%s%.,]+%)") then
local f = str:gmatch("[%d.]+")
r = (f() or 0) / 0xff
g = (f() or 0) / 0xff
b = (f() or 0) / 0xff
a = f() or 1
else
error(("bad color string '%s'"):format(str))
end
return r * mul, g * mul, b * mul, a * mul
end
function lume.rgba(color)
local a = math_floor((color / 16777216) % 256)
local r = math_floor((color / 65536) % 256)

View File

@ -565,6 +565,23 @@ tests["lume.ripairs"] = function()
tester.test.error(lume.ripairs, nil)
end
-- lume.color
tests["lume.color"] = function()
testeq({ lume.color("#ff0000") }, { 1, 0, 0, 1 } )
testeq({ lume.color("#00ff00") }, { 0, 1, 0, 1 } )
testeq({ lume.color("#0000ff") }, { 0, 0, 1, 1 } )
testeq({ lume.color("rgb( 255, 255, 255 )") }, { 1, 1, 1, 1 } )
testeq({ lume.color("rgb (0, 0, 0)") }, { 0, 0, 0, 1 } )
testeq({ lume.color("rgba(255, 255, 255, .5)") }, { 1, 1, 1, .5 } )
testeq({ lume.color("#ffffff", 2) }, { 2, 2, 2, 2 } )
testeq({ lume.color("rgba(255, 255, 255, 1)", 3) }, { 3, 3, 3, 3 } )
tester.test.error(lume.color, "#ff00f")
tester.test.error(lume.color, "#xyzxyz")
tester.test.error(lume.color, "rgba(hello)")
tester.test.error(lume.color, "rgba()")
tester.test.error(lume.color, "rgba(1, 1, 1, 1")
end
-- lume.rgba
tests["lume.rgba"] = function()
local r, g, b, a = lume.rgba(0x12345678)