diff --git a/lume.lua b/lume.lua index d157c2a..18074e4 100644 --- a/lume.lua +++ b/lume.lua @@ -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) diff --git a/test/test_lume.lua b/test/test_lume.lua index f446276..bf9d58a 100644 --- a/test/test_lume.lua +++ b/test/test_lume.lua @@ -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)