Skip to content

Commit

Permalink
feat(calc): add contrast_ratio fn
Browse files Browse the repository at this point in the history
  • Loading branch information
JiatLn committed Aug 25, 2023
1 parent 93728d5 commit f5ac082
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 1 deletion.
51 changes: 51 additions & 0 deletions src/color_calc/contrast_ratio.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use crate::Color;

/// Computes the WCAG contrast ratio between two colors
///
/// Reference: [W3C contrast ratio](https://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef)
///
/// **Tips**: A minimum contrast of 4.5:1 is [recommended](http://www.w3.org/TR/WCAG20-TECHS/G18.html) to ensure that text is still readable against a background color.
///
/// # Example
///
/// ```
/// use color_art::{color, contrast_ratio};
///
/// let color1 = color!(#fefe0e);
/// let color2 = color!(#fff);
/// let contrast = contrast_ratio(&color1, &color2);
///
/// assert_eq!(contrast, 1.0826287103122008);
pub fn contrast_ratio(color1: &Color, color2: &Color) -> f64 {
let l1 = color1.luminance();
let l2 = color2.luminance();
let l_max = l1.max(l2);
let l_min = l1.min(l2);
(l_max + 0.05) / (l_min + 0.05)
}

#[cfg(test)]
mod tests {
use crate::*;

#[test]
fn test_distance() {
let color1 = color!(#000);
let color2 = color!(#fff);

let contrast = contrast_ratio(&color1, &color2);
assert_eq!(contrast, 21.0);

let color1 = color!(#fefe0e);
let color2 = color!(#fff);

let contrast = contrast_ratio(&color1, &color2);
assert_eq!(contrast, 1.0826287103122008);

let color1 = Color::from_name("purple").unwrap();
let color2 = Color::from_name("pink").unwrap();

let contrast = contrast_ratio(&color1, &color2);
assert_eq!(contrast, 6.124225406859997);
}
}
1 change: 1 addition & 0 deletions src/color_calc/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub mod blend;
pub mod distance;
pub mod delta_e;
pub mod contrast_ratio;

pub use blend::BlendMode;
3 changes: 2 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@ mod utils;

pub use color::Color;
pub use color_calc::blend::*;
pub use color_calc::distance::*;
pub use color_calc::contrast_ratio::*;
pub use color_calc::delta_e::*;
pub use color_calc::distance::*;
pub use color_space::ColorSpace;
use data::alpha_hex_map::ALPHA_HEX_MAP;
use data::chinese_color::CHINESE_COLOR_HASHMAP as CHINESE_COLOR;
Expand Down

0 comments on commit f5ac082

Please sign in to comment.