chroma_rust/color/
alpha.rs

1use crate::Color;
2
3impl Color {
4    /// Get color alpha.
5    ///
6    /// # Examples
7    /// ```
8    /// use chroma_rust::Color;
9    /// let color = Color::from("#abcdef");
10    /// assert_eq!(color.alpha(), 1.);
11    /// ```
12    pub fn alpha(&self) -> f64 {
13        self.rgba.3
14    }
15    /// Set color alpha.
16    ///
17    /// - If alpha is less than 0, it will be set to 0.
18    /// - If alpha is greater than 1, it will be set to 1.
19    ///
20    /// # Example
21    /// ```
22    /// use chroma_rust::Color;
23    /// let mut color = Color::from("#7760BF");
24    /// let color = color.set_alpha(0.5);
25    /// assert_eq!(color.alpha(), 0.5);
26    /// ```
27    pub fn set_alpha(&mut self, alpha: f64) -> &mut Self {
28        if alpha > 1.0 {
29            self.rgba.3 = 1.0;
30        } else if alpha < 0.0 {
31            self.rgba.3 = 0.0;
32        } else {
33            self.rgba.3 = alpha;
34        }
35        self
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use super::*;
42
43    #[test]
44    fn test_color_alpha() {
45        let color = Color::from("#abcdef");
46        assert_eq!(color.alpha(), 1.);
47    }
48
49    #[test]
50    fn test_color_set_alpha() {
51        let mut color = Color::from("#7760BF");
52        let color = color.set_alpha(0.5);
53        assert_eq!(color.alpha(), 0.5);
54    }
55}