'Will white always contrast with a colour with luminance < 0.5?
I'm trying to build a script which alters text depending on the background colour. I suppose this is more of a question about the nature of colours than one on programming.
I've followed this as a guideline to calculate luminance. However, unlike the case in that question, rather than finding the contrast between two colours, I'd like to get a reasonably contrasting colour from one colour and a provided contrast.
I'm aware there are likely to be infinitely many colours that contrast well with any background: the approach I've taken is to set the text colour to white if the luminance is < 0.5, or black if > 0.5. This makes an assumption that black and white would always contrast reasonably with colours with luminance greater or less than 0.5 respectively, and I'm not sure if this holds true.
Would there be a better way to decide a colour to pick? I do not want the text to alter too drastically for every small colour change, and would much rather have just two colours, but am not sure if black and white are the answers.
Edit: here's a minimal reproducible code example:
def calculate_luminance(r, g, b):
rgb_new = []
for component in [r, g, b]:
modified_component = component/12.92 if component <= 0.03928 else ((component + 0.055)/1.055)**2.4
rgb_new.append(modified_component)
return 0.2126*rgb_new[0] + 0.7152*rgb_new[1] + 0.0722*rgb_new[2]
def get_readable_text_colours(colours):
new_colours = []
for colour in colours:
luminance = calculate_luminance(*colour)
if luminance > 0.5:
new_colours.append([0, 0, 0])
else:
new_colours.append([1, 1, 1])
return new_colours
print(get_readable_text_colours([[0, 0, 0], [1, 1, 1], [0.5, 0.15, 0.2], [0, 1, 1]]))
The function calculate_luminance has its values taken from the Web Content Accessibility Guidelines 2.1 The function get_readable_text_colours accepts a list-of-list of colours in RGB form that have been normalised to the range of [0, 1].
Output:
[[1, 1, 1], [0, 0, 0], [1, 1, 1], [0, 0, 0]]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
