Skip to content

Commit 033fb8b

Browse files
committed
add relative_luminance() and contrast_ratio() to Color
1 parent 623497e commit 033fb8b

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

src/color/lut.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@
55

66
#![allow(dead_code)]
77

8-
// Compile-time params
9-
108
use std::sync::OnceLock;
119

1210
/// linear -> sRGB table size

src/color/model.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,24 @@ impl Color {
178178
dst
179179
}
180180

181+
#[must_use]
182+
#[inline]
183+
pub fn relative_luminance(self) -> f32 {
184+
let [r, g, b, _] = self.into_linear::<f32>();
185+
0.2126 * r + 0.7152 * g + 0.0722 * b
186+
}
187+
188+
#[must_use]
189+
#[inline]
190+
pub fn contrast_ratio(self, other: Color) -> f32 {
191+
let (l1, l2) = {
192+
let a = self.relative_luminance();
193+
let b = other.relative_luminance();
194+
if a >= b { (a, b) } else { (b, a) }
195+
};
196+
(l1 + 0.05) / (l2 + 0.05)
197+
}
198+
181199
#[must_use]
182200
#[inline]
183201
pub fn with_alpha(self, a: u8) -> Self {
@@ -233,6 +251,8 @@ impl Color {
233251
format!("{:02x}{:02x}{:02x}{:02x}", self.r, self.g, self.b, self.a)
234252
}
235253

254+
// TODO make rest of the f32/f64 funcs generic with Float
255+
236256
#[must_use]
237257
#[inline]
238258
pub fn from_hsl_f32(hsl: [f32; 3]) -> Self {

0 commit comments

Comments
 (0)