Skip to main content

primitives/foundation/colorspace/
rgba.rs

1use super::*;
2use std::fmt;
3
4/// Rgba color representation with u8 components
5#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
6pub struct RgbaColor {
7    /// Red component
8    pub red: u8,
9    /// Green component
10    pub green: u8,
11    /// Blue component
12    pub blue: u8,
13    /// Alpha component
14    pub alpha: u8,
15}
16
17impl fmt::Display for RgbaColor {
18    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19        write!(
20            f,
21            "rgba({}, {}, {}, {})",
22            self.red, self.green, self.blue, self.alpha
23        )
24    }
25}
26
27impl RgbaColor {
28    /// Create new Rgba color with parameters
29    pub fn new(red: u8, green: u8, blue: u8, alpha: u8) -> Self {
30        Self {
31            red,
32            green,
33            blue,
34            alpha,
35        }
36    }
37}
38
39// RGBAu8 -> RGB
40impl From<RgbaColor> for Color {
41    fn from(rgba: RgbaColor) -> Self {
42        Color {
43            red: rgba.red as Float / 255.0,
44            green: rgba.green as Float / 255.0,
45            blue: rgba.blue as Float / 255.0,
46            alpha: rgba.alpha as Float / 255.0,
47        }
48    }
49}
50
51impl From<Color> for RgbaColor {
52    fn from(color: Color) -> Self {
53        RgbaColor {
54            red: (color.red * 255.0).round() as u8,
55            green: (color.green * 255.0).round() as u8,
56            blue: (color.blue * 255.0).round() as u8,
57            alpha: (color.alpha * 255.0).round() as u8,
58        }
59    }
60}