freya_core/style/
fill.rs

1use std::fmt::{
2    self,
3    Pointer,
4};
5
6use freya_engine::prelude::Paint;
7use torin::prelude::Area;
8
9use crate::{
10    prelude::Color,
11    style::gradient::{
12        ConicGradient,
13        LinearGradient,
14        RadialGradient,
15    },
16};
17
18#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
19#[derive(Clone, Debug, PartialEq)]
20pub enum Fill {
21    Color(Color),
22    LinearGradient(Box<LinearGradient>),
23    RadialGradient(Box<RadialGradient>),
24    ConicGradient(Box<ConicGradient>),
25}
26
27impl Fill {
28    pub fn set_a(&mut self, a: u8) {
29        if let Fill::Color(color) = self {
30            // Only actually change the alpha if its non-transparent
31            if *color != Color::TRANSPARENT {
32                *color = color.with_a(a);
33            }
34        }
35    }
36
37    pub fn apply_to_paint(&self, paint: &mut Paint, area: Area) {
38        match &self {
39            Fill::Color(color) => {
40                paint.set_color(*color);
41            }
42            Fill::LinearGradient(gradient) => {
43                paint.set_shader(gradient.into_shader(area));
44            }
45            Fill::RadialGradient(gradient) => {
46                paint.set_shader(gradient.into_shader(area));
47            }
48            Fill::ConicGradient(gradient) => {
49                paint.set_shader(gradient.into_shader(area));
50            }
51        }
52    }
53}
54
55impl Default for Fill {
56    fn default() -> Self {
57        Self::Color(Color::default())
58    }
59}
60
61impl From<Color> for Fill {
62    fn from(color: Color) -> Self {
63        Fill::Color(color)
64    }
65}
66
67impl fmt::Display for Fill {
68    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
69        match self {
70            Self::Color(color) => color.fmt(f),
71            Self::LinearGradient(gradient) => gradient.as_ref().fmt(f),
72            Self::RadialGradient(gradient) => gradient.as_ref().fmt(f),
73            Self::ConicGradient(gradient) => gradient.as_ref().fmt(f),
74        }
75    }
76}