embedded_layout/utils/
rect_helper.rs

1//! `Rectangle` utility methods
2//!
3//! This module implements a few useful extensions to `Rectangle`.
4use embedded_graphics::{geometry::AnchorPoint, prelude::*, primitives::Rectangle};
5
6/// The trait that describes the extension methods.
7pub trait RectExt {
8    /// Return the bounding `Rectangle` that encompasses both `Rectangles`
9    fn enveloping(&self, other: &Rectangle) -> Rectangle;
10}
11
12impl RectExt for Rectangle {
13    #[inline]
14    fn enveloping(&self, other: &Rectangle) -> Rectangle {
15        Rectangle::with_corners(
16            Point::new(
17                self.top_left.x.min(other.top_left.x),
18                self.top_left.y.min(other.top_left.y),
19            ),
20            Point::new(
21                self.anchor_point(AnchorPoint::BottomRight)
22                    .x
23                    .max(other.anchor_point(AnchorPoint::BottomRight).x),
24                self.anchor_point(AnchorPoint::BottomRight)
25                    .y
26                    .max(other.anchor_point(AnchorPoint::BottomRight).y),
27            ),
28        )
29    }
30}
31
32#[cfg(test)]
33mod test {
34    use crate::prelude::*;
35    use embedded_graphics::{prelude::*, primitives::Rectangle};
36
37    #[test]
38    fn test_enveloping() {
39        let rect0 = Rectangle::with_corners(Point::new(-1, -1), Point::new(0, 0));
40        let rect1 = Rectangle::with_corners(Point::zero(), Point::new(1, 1));
41        let rect2 = Rectangle::with_corners(Point::zero(), Point::new(2, 2));
42
43        assert_eq!(rect2, rect2.enveloping(&rect1));
44        assert_eq!(rect2, rect1.enveloping(&rect2));
45        assert_eq!(
46            Rectangle::with_corners(Point::new(-1, -1), Point::new(2, 2),),
47            rect0.enveloping(&rect2)
48        );
49    }
50}