rive_rs/shapes/paint/
color.rs
1use std::fmt;
6
7#[derive(Clone, Copy, Default, Eq, PartialEq)]
8pub struct Color32(pub u32);
9
10impl Color32 {
11 pub fn new(val: u32) -> Self {
12 Self(val)
13 }
14
15 pub fn from_argb(alpha: u8, red: u8, green: u8, blue: u8) -> Self {
16 Self((alpha as u32) << 24 | (red as u32) << 16 | (green as u32) << 8 | blue as u32)
17 }
18
19 pub fn alpha(self) -> u8 {
20 ((0xFF000000 & self.0) >> 24) as u8
21 }
22
23 pub fn red(self) -> u8 {
24 ((0x00FF0000 & self.0) >> 16) as u8
25 }
26
27 pub fn green(self) -> u8 {
28 ((0x0000FF00 & self.0) >> 8) as u8
29 }
30
31 pub fn blue(self) -> u8 {
32 (0x000000FF & self.0) as u8
33 }
34
35 pub fn opacity(self) -> f32 {
36 self.alpha() as f32 / u8::MAX as f32
37 }
38
39 pub fn with_alpha(self, alpha: u8) -> Self {
40 Self::from_argb(alpha, self.red(), self.green(), self.blue())
41 }
42
43 pub fn with_opacity(self, opacity: f32) -> Self {
44 self.with_alpha((opacity * 255.0).round() as u8)
45 }
46
47 pub fn mul_opacity(self, opacity: f32) -> Self {
48 self.with_opacity(self.opacity() * opacity)
49 }
50
51 pub fn lerp(self, other: Self, ratio: f32) -> Self {
52 fn lerp(a: u8, b: u8, ratio: f32) -> u8 {
53 (a as f32 + ((b as f32 - a as f32) * ratio)).round() as u8
54 }
55
56 Self::from_argb(
57 lerp(self.alpha(), other.alpha(), ratio),
58 lerp(self.red(), other.red(), ratio),
59 lerp(self.green(), other.green(), ratio),
60 lerp(self.blue(), other.blue(), ratio),
61 )
62 }
63}
64
65impl fmt::Debug for Color32 {
66 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67 f.debug_struct("Color32")
68 .field("alpha", &self.alpha())
69 .field("red", &self.red())
70 .field("green", &self.green())
71 .field("blue", &self.blue())
72 .finish()
73 }
74}
75
76impl From<u32> for Color32 {
77 fn from(val: u32) -> Self {
78 Self(val)
79 }
80}