Forum Archive

[Lab] determine black or white color to draw text onto a CSS color

Phuket2

I made the most basic of functions to try to decide based on a CSS color background, what color to use for text on the background so it's not lost ( only black or white). The one below, seems to work for quick and dirty uses. It's just fun. But I know a lot more can be done mathematically with the r,g,b components. I tried a few silly things with sliders to filter the CSS colours also. Anyway have a gist here.
The function that I did is below. Yes, it's crap, but it sort of works if you have nothing else. Maybe someone with time on their hands can come up with something more exacting.

def safe_color(css_color):
    rgba = ui.parse_color(css_color)
    r = rgba[0] 
    g = rgba[1]
    b = rgba[2] 
    if (((r + g + b) / 3 ) > .55) :
        return 'black'
    else:
        return 'white'

Output from gist

ccc

Maybe return 'black' if sum(rgba[:3]) / 3 > .55 else 'white' ;-)

cvp

Or return 'black' if sum(rgba[:3]) > 1.65 else 'white' ;-)

ccc

return int(sum(rgba[:3]) <= 1.65)

Webmaster4o

One tip for making text more readable is something the Material Design guidelines recommend: While white text should be rgba(255, 255, 255, 1), but black text should be rgba(0, 0, 0, 0.87). The slight opacity in the black makes it much more readable on colored backgrounds.

ccc

return int(sum(rgba[:3]) <= 1.65) or (0, 0, 0, .87)

Phuket2

Thanks guys. I have made a snippet for myself using
return int(sum(rgba[:3]) <= 1.65) or (0, 0, 0, .87)

I know it's not a big deal, but it's nice to have these things handy and to be a no brainer even if you ultimately tweak the colors. Will take a closer look at what @Webmaster4o did later , as I think he did some complimentary color work when he was working on themes.

Phuket2

@ccc , I did try briefly to simplify the expression. I was trying to use unpacking, slicing didn't occur to me 😱I didn't search stackflow, because I was playing with components also. But it seems like the average checked against a threshold seems to work ok. But I am glad you call us out on it. It does make me think before I post stuff. When I posted it, I was almost certain that I would be hearing from you. I was grinning for 5 mins when I saw your reply 😬😬😬

ccc

Don't think toooo hard before you post to the forum... we love to see your crazy ideas in their raw form. But do consider running Check Style and Analyze (PyFlakes) as they find simple issues (like your unused variable) and push you to make your code more readable. I have become big fan of autopep8 on my Mac. It would be cool to see that level of automatic reformatting as an option in Pythonista.