haussmann/graphics/colours.rs
1// This file is part of "haussmann"
2// Under the MIT License
3// Copyright (c) 2023 Antonin Hérault
4
5//! Structures to store and convert hexadecimal to RGBA colour values, and
6//! colour constants.
7
8/// Blue colour constant (alpha = 255).
9pub const BLUE: RGBA = RGBA {
10 r: 0,
11 g: 0,
12 b: 255,
13 a: 255,
14};
15/// Green colour constant (alpha = 255).
16pub const GREEN: RGBA = RGBA {
17 r: 0,
18 g: 255,
19 b: 0,
20 a: 255,
21};
22/// Red colour constant (alpha = 255).
23pub const RED: RGBA = RGBA {
24 r: 255,
25 g: 0,
26 b: 0,
27 a: 255,
28};
29/// Transparent colour constant (alpha = 0).
30pub const TRANSPARENT: RGBA = RGBA {
31 r: 0,
32 g: 0,
33 b: 0,
34 a: 0,
35};
36
37/// Colour with red, green and blue values + an alpha channel.
38#[derive(Debug, Copy, Clone, Eq, PartialEq)]
39pub struct RGBA {
40 /// Red part of the colour corresponding to the first two bytes of an
41 /// hexadecimal colour value.
42 ///
43 /// Must be in range from 0 to 255.
44 pub r: u32,
45 /// Green part of the colour corresponding to the third and fourth bytes of
46 /// an hexadecimal colour value.
47 ///
48 /// Must be in range from 0 to 255.
49 pub g: u32,
50 /// Blue part of the colour corresponding to the fifth and sixth bytes of an
51 /// hexadecimal colour value.
52 ///
53 /// Must be in range from 0 to 255.
54 pub b: u32,
55 /// Alpha part of the colour corresponding to the seventh and eighth bytes
56 /// of an hexadecimal colour value.
57 ///
58 /// Must be in range from 0 to 255.
59 pub a: u32,
60}
61
62impl Default for RGBA {
63 fn default() -> Self {
64 RGBA {
65 r: 0,
66 g: 0,
67 b: 0,
68 a: 0,
69 }
70 }
71}
72
73impl RGBA {
74 /// Creates a new `RGBA` object.
75 ///
76 /// `r`, `g`, `b` and `a` are in range 0 to 255, where 0 is the non-colour
77 /// (black) and 255 the full colour (red, green or blue). For `a` being the
78 /// alpha channel, 0 transparent and 255 is completely visible.
79 pub fn new(r: u32, g: u32, b: u32, a: u32) -> Self {
80 Self { r, g, b, a }
81 }
82
83 /// Creates a new `RGBA` object from an hexadecimal value having an alpha
84 /// channel.
85 ///
86 /// Converts the hexadecimal `value` into a "RGBA" structure.
87 pub fn from_hex(value: u32) -> Self {
88 Self {
89 r: ((value >> 24) & 0xFF) / 255, // RR byte
90 g: ((value >> 16) & 0xFF) / 255, // GG byte
91 b: ((value >> 8) & 0xFF) / 255, // BB byte
92 a: ((value) & 0xFF) / 255, // AA byte
93 }
94 }
95
96 /// Converts the `RGBA` values into an hexadecimal value.
97 pub fn to_hex(&self) -> u32 {
98 (self.a << 24) | (self.b << 16) | (self.g << 8) | self.r
99 }
100}