HexToRGB

From Wowpedia
Jump to: navigation, search
This is a user-defined function that you can copy and paste into your addon.

Takes a hex string (must be 6 char long!) and converts it to a RGB set (0-255)

local function HexToRGB(hex)
	local rhex, ghex, bhex = string.sub(hex, 1, 2), string.sub(hex, 3, 4), string.sub(hex, 5, 6)
	return tonumber(rhex, 16), tonumber(ghex, 16), tonumber(bhex, 16)
end

Alternative version

Takes a hex string (must be 3 or 6 chars long!) and converts it to a RGB set (0-255). If hex is invalid, return black (0,0,0).

local function HexToRGB(hex)
    if type(hex) == "string" then
         local m = #hex == 3 and 17 or (#hex == 6 and 1 or 0)
         local rhex, ghex, bhex = hex:match('^(%x%x?)(%x%x?)(%x%x?)$')
         if rhex and m > 0 then
              return tonumber(rhex, 16) * m, tonumber(ghex, 16) * m, tonumber(bhex, 16) * m
         end
    end
    return 0, 0, 0
end