如何在Lua中将HSL转换为RGB

我想将HSL值转换为RGB,以便在Love2D中轻松生成随机颜色,但我找不到如何做到这一点。我已经查阅了维基百科,但真的一无所知,我还在浏览Stack Overflow,但没有找到针对Lua的任何东西。如果可能,我想函数输入3个值并返回一个带有table.r、table.b、table.g的表格,以便我可以调用function().r等等。我该如何做呢?

Stack Overflow不允许我发布这个问题,除非我添加更多信息,所以让我们看看,我不想随机化RGB值的原因是我只想更改色调,而不影响饱和度/亮度。我认为HSL会是实现这个目的的完美方式,因为我只需随机一种色调颜色,然后将其转换为RGB,而RGB则是在Love2D中定义颜色的方式。

点赞
用户9095619
用户9095619

我在 https://github.com/unek/loveframes-snap-theme/blob/master/color.lua 中找到了你想要的函数。

以下是你需要提取的部分:

-- 需要让 hsl2rgb 函数正常运作
local function hue2rgb(p, q, t)
    if t < 0   then t = t + 1 end
    if t > 1   then t = t - 1 end
    if t < 1/6 then return p + (q - p) * 6 * t end
    if t < 1/2 then return q end
    if t < 2/3 then return p + (q - p) * (2/3 - t) * 6 end
    return p
end

-- 以下是你需要的函数 --

local function hsl2rgb(h, s, l)
    local r, g, b

    local h = h / 360

    if s == 0 then
        r, g, b = l, l, l
    else
        local q = (l < 0.5) and l * (1 + s) or l + s - l * s
        local p = l * 2 - q

        r = hue2rgb(p, q, h + 1/3)
        g = hue2rgb(p, q, h)
        b = hue2rgb(p, q, h - 1/3)
    end

    return {r=r, g=g, b=b}
end

请注意,RGB 值将会在 [0-1] 范围内。

2020-08-08 11:58:23