Skip to content

Instantly share code, notes, and snippets.

@siasur
Created April 27, 2016 08:42
Show Gist options
  • Save siasur/2ebd9dc13cddecac69ce548c6dffa192 to your computer and use it in GitHub Desktop.
Save siasur/2ebd9dc13cddecac69ce548c6dffa192 to your computer and use it in GitHub Desktop.
Hex2Color Converter - Convert (extended) hexadecimal colors to its RGBA counterpart
-- Hex2Color Converter
-- Copyright (c) 2016 Mischa Behrend <https://github.com/siasur>
--[[
Dieses kleine Codesnippet konvertiert (erweiterte) Hexadezimalfarben in ihre entsprechenden RGBA Werte.
Erweitert bedeutet, dass die Hexadezimalwerte (vom Standard abweichend) um eine weitere Stelle für den
Alphakanal ergänzt werden dürfen. Die führende Raute kann bei bedarf weggelassen werden.
This little codesnippet will convert (extended) hexadecimal colors to its RGBA counterpart. Extended
means that you can (different to the default) append a fourth value for the alpha channel.
The leading hash can be omitted.
Example:
#451278 --[ HEX2Color ]--> 69, 18, 120, 0
]]
local function HEX2Color(--[[ String ]] _hex)
if not ( _hex:match('^#?[0-9a-f]+$') ) then
error(_hex .. " is not a hexadecimal value!")
end
_hex = _hex:gsub("#", "")
if not (#_hex == 3 or ( (3 < #_hex and #_hex < 9) and #_hex % 2 == 0)) then
error(_hex .. " does not have the correct length (3, 4, 6 or 8)")
end
local color = { }
local step = 1
local steps = (#_hex < 5) and 1 or 2
local hasNextStep = true
while (hasNextStep) do
local hexval = _hex:sub(step+(((steps%2-1)*-1)*step-1)+(steps%2), step*steps)
if (hexval ~= null and hexval ~= "") then
color[step] = tonumber(hexval:rep(steps%2+1), 16)
step = step+1
else
color[step] = 0
hasNextStep = false
end
end
return color[1], color[2], color[3], color[4]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment