simple_layout/
padding.rs

1use std::marker::PhantomData;
2use std::num::Saturating;
3
4use embedded_graphics::draw_target::DrawTarget;
5use embedded_graphics::geometry::Point;
6use embedded_graphics::prelude::{PixelColor, Size};
7use embedded_graphics::primitives::Rectangle;
8
9use crate::prelude::Layoutable;
10use crate::ComponentSize;
11
12///
13/// Adjust placement of a component by adding/removing additional offsets
14///
15/// # Arguments
16///
17/// * `layoutable`: element to place
18/// * `top`: adjustment to the top
19/// * `right`: adjustment on the right
20/// * `bottom`: adjustment to the bottom
21/// * `left`: adjustment on the left
22///
23/// returns: impl Layoutable<C>+Sized
24///
25/// # Examples
26///
27/// ```
28/// use embedded_graphics::geometry::Point;
29/// use embedded_graphics::mono_font::iso_8859_1::FONT_6X12;
30/// use embedded_graphics::mono_font::MonoTextStyle;
31/// use embedded_graphics::pixelcolor::BinaryColor;
32/// use embedded_graphics::text::Text;
33/// use simple_layout::prelude::padding;
34/// let adjusted_text = padding(Text::new("-", Point::zero(), MonoTextStyle::new(&FONT_6X12, BinaryColor::On)), -2, 1, -1, 1);
35/// ```
36pub fn padding<C: PixelColor, L: Layoutable<C>>(
37    layoutable: L,
38    top: i32,
39    right: i32,
40    bottom: i32,
41    left: i32,
42) -> impl Layoutable<C> {
43    Padding {
44        layoutable,
45        top,
46        right,
47        bottom,
48        left,
49        p: Default::default(),
50    }
51}
52
53struct Padding<C: PixelColor, L: Layoutable<C>> {
54    layoutable: L,
55    top: i32,
56    right: i32,
57    bottom: i32,
58    left: i32,
59    p: PhantomData<C>,
60}
61
62impl<C: PixelColor, L: Layoutable<C>> Layoutable<C> for Padding<C, L> {
63    fn size(&self) -> ComponentSize {
64        let ComponentSize { width, height } = self.layoutable.size();
65        ComponentSize {
66            width: width + (self.left + self.right),
67            height: height + (self.top + self.bottom),
68        }
69    }
70
71    fn draw_placed<DrawError>(
72        &self,
73        target: &mut impl DrawTarget<Color = C, Error = DrawError>,
74        position: Rectangle,
75    ) -> Result<(), DrawError> {
76        let Rectangle {
77            top_left: Point { x, y },
78            size: Size { width, height },
79        } = position;
80        let position = Rectangle {
81            top_left: Point {
82                x: x + self.left,
83                y: y + self.top,
84            },
85            size: Size {
86                width: (Saturating(width as i32) - Saturating(self.left + self.right)).0 as u32,
87                height: (Saturating(height as i32) - Saturating(self.top + self.bottom)).0 as u32,
88            },
89        };
90        self.layoutable.draw_placed(target, position)
91    }
92}