Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add hex colour support (issue #29) #56

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

ellen364
Copy link

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.

set_pixel function accepts a hex colour code.
@Gadgetoid
Copy link
Member

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants