Skip to content

Commit

Permalink
Use relative luminance to pick black or white text (#494)
Browse files Browse the repository at this point in the history
When choosing if the text on top of a color should be black or white,
HSL didn't do a great job for colors with a bright green color channel.
It turns out that green accounts for most of typical human vision. This
probably explains why `#FFFF00` looks brighter than `#0000FF`, even
though both have the same L value for HSL.

Reference: https://en.wikipedia.org/wiki/Relative_luminance
  • Loading branch information
spenserblack authored Jan 8, 2025
1 parent f88b2fa commit f8481a8
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions gengo-bin/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,11 +232,12 @@ impl CLI {

#[cfg(feature = "color")]
fn is_bright(r: u8, g: u8, b: u8) -> bool {
// NOTE Adapted from https://css-tricks.com/converting-color-spaces-in-javascript/#aa-rgb-to-hsl
let min: u16 = [r, g, b].into_iter().min().unwrap().into();
let max: u16 = [r, g, b].into_iter().max().unwrap().into();
let lightness = (max + min) / 2;
lightness > 0x7F
// NOTE See https://en.wikipedia.org/wiki/Relative_luminance
[(r, 0.2126), (g, 0.7152), (b, 0.0722)]
.into_iter()
.map(|(channel, weight)| (f32::from(channel) / 255.0) * weight)
.sum::<f32>()
> 0.5
}

#[cfg(feature = "color")]
Expand Down

0 comments on commit f8481a8

Please sign in to comment.