unicorn-hat-hd
unicorn-hat-hd copied to clipboard
Add hex colour support (issue #29)
Pull request addresses issue #29.
The issue is a few years old, so not sure if you're still interested in hex colour support. But since I had this code, figured I'd open a PR.
This implementation expects hex colour codes to be prefixed with #
(to simplify handling of hex colours vs named colours like "green"). The hex number itself must be 3 or 6 digits (e.g. #AAA or #010101), while the hex letters can be upper or lower case.
Experimenting in a shell suggests it's fine for Python 2.7, which I noticed is supported by unicorn-hat-hd.
Sorry for not getting back to you sooner.
This is great, thank you.
The one thing I'd change is to drop the dependency on regex and simply try to parse the colour as-is, catching any exception and using that to detect invalid colours.
Something like, and this is off the top of my head so I'm sorry if I've missed something:
def hex_to_rgb(color):
"""Convert hex color code to RGB.
:param color: 3 or 6 digit hex number prefixed with #
"""
try:
if len(color) == 7:
return (
int(color[1:3], base=16),
int(color[3:5], base=16),
int(color[5:7], base=16),
)
elif len(color) == 4:
return (
int(color[1] * 2, base=16),
int(color[2] * 2, base=16),
int(color[3] * 2, base=16),
)
except IndexError, ValueError:
pass
raise ValueError("Invalid hex color.")
return r, g, b
This would also be (possibly much) faster, which is- I suppose- of moderate importance in a 16x16 display.