setColor Hexadecimal snippet
Posted: Thu May 31, 2012 9:36 am
I'm not an amazing programmer by any means, and so I was rather proud when I managed to write this snippet from scratch. It's not particularly useful, but if you come from a web design background and/or you prefer to work with hexes for colours you may find some use for it.
If you wish to change say, the alpha value over time you can use something like this:
It adds a little, perhaps unnecessary overhead, but I find it far easier to work with hexes, and eh, I ventured into unknown territory and managed to actually get it working. Feel free to use if you can find any reason too.
Oh, and there's no preset cornflower blue
Code: Select all
function ink(hex)
--convert hexadecimal (accepts 6 or 8 characters)
local function convertHex(hex)
local splitToRGB = {}
if # hex < 6 then hex = hex .. string.rep("F", 6 - # hex) end --flesh out bad hexes
for x = 1, # hex - 1, 2 do
table.insert(splitToRGB, tonumber(hex:sub(x, x + 1), 16)) --convert hexes to dec
if splitToRGB[# splitToRGB] < 0 then slpitToRGB[# splitToRGB] = 0 end --prevents negative values
end
return unpack(splitToRGB)
end
--predefined colours ("" works for white for convenience)
if hex == "red" then
hex = "FF3333FF"
elseif hex == "green" then
hex = "33FF33FF"
elseif hex == "blue" then
hex = "3333FFFF"
elseif hex == "white" or hex == "" then
hex = "FFFFFFFF"
elseif hex == "black" then
hex = "333333FF"
end
love.graphics.setColor(convertHex(hex))
end
Code: Select all
object.alpha = 0 + increment * dt
object.alpha = string.format("%x", math.floor(v.alpha)) --prepare hex
if # object.alpha == 1 then object.alpha = "0" .. object.alpha end --prefix 0 on low alpha values (below 10). This is due to the nature of %x
ink("ffffff" .. object.alpha)
Oh, and there's no preset cornflower blue