Expose relative_luminance as part of Color

This commit is contained in:
Héctor Ramón Jiménez 2025-08-06 05:55:33 +02:00
parent 0037699dda
commit 3f22d5683a
No known key found for this signature in database
GPG key ID: 7CC46565708259A7
2 changed files with 9 additions and 8 deletions

View file

@ -195,6 +195,13 @@ impl Color {
..self
}
}
/// Returns the relative luminance of the [`Color`].
/// https://www.w3.org/TR/WCAG21/#dfn-relative-luminance
pub fn relative_luminance(self) -> f32 {
let linear = self.into_linear();
0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2]
}
}
impl From<[f32; 3]> for Color {

View file

@ -716,17 +716,11 @@ fn is_readable(a: Color, b: Color) -> bool {
// https://www.w3.org/TR/WCAG21/#dfn-contrast-ratio
fn relative_contrast(a: Color, b: Color) -> f32 {
let lum_a = relative_luminance(a);
let lum_b = relative_luminance(b);
let lum_a = a.relative_luminance();
let lum_b = b.relative_luminance();
(lum_a.max(lum_b) + 0.05) / (lum_a.min(lum_b) + 0.05)
}
// https://www.w3.org/TR/WCAG21/#dfn-relative-luminance
fn relative_luminance(color: Color) -> f32 {
let linear = color.into_linear();
0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2]
}
// https://en.wikipedia.org/wiki/Oklab_color_space#Conversions_between_color_spaces
fn to_oklch(color: Color) -> Oklch {
let [r, g, b, alpha] = color.into_linear();