chroma_rust/ops/
darken.rs

1use crate::{utils::conversion, Color};
2
3// Corresponds roughly to RGB brighter/darker
4static KN: f64 = 18.;
5
6impl Color {
7    /// Darken a color by a given amount.
8    ///
9    /// Default amount is 1.0.
10    ///
11    /// Example:
12    /// ```
13    /// use chroma_rust::Color;
14    /// Color::from("hotpink").darken(Some(2.)); // #930058
15    /// ```
16    pub fn darken(&self, amount: Option<f64>) -> Color {
17        let amount = amount.unwrap_or(1.);
18        let lab = self.mode("lab");
19        let alpha = self.alpha();
20        let (l, a, b) = (lab[0] - KN * amount, lab[1], lab[2]);
21        let (r, g, b, _) = conversion::lab::lab2rgb((l, a, b));
22        Color::new(r, g, b, alpha)
23    }
24    /// alias for darken
25    pub fn darker(&self, amount: Option<f64>) -> Color {
26        let amount = amount.unwrap_or(1.);
27        Color::darken(&self, Some(amount))
28    }
29
30    /// Brighten a color by a given amount.
31    pub fn brighten(&self, amount: Option<f64>) -> Color {
32        let amount = amount.unwrap_or(1.);
33        Color::darken(&self, Some(amount * -1.))
34    }
35    /// alias for brighten
36    pub fn brighter(&self, amount: Option<f64>) -> Color {
37        let amount = amount.unwrap_or(1.);
38        Color::brighten(&self, Some(amount))
39    }
40}
41
42#[cfg(test)]
43mod tests {
44    use crate::Color;
45
46    #[test]
47    fn test_darken_color() {
48        let color = Color::from("hotpink");
49        let darkened = color.darken(None);
50        assert_eq!(darkened.name(), "#c93384");
51
52        let color = Color::from("hotpink");
53        let darkened = color.darken(Some(2.));
54        assert_eq!(darkened.name(), "#930058");
55    }
56
57    #[test]
58    fn test_brighten_color() {
59        let color = Color::from("#7760BF");
60        let brightened = color.brighten(None);
61        assert_eq!(brightened.name(), "#a98ef2"); // #b5a9dc
62    }
63}