iced_core/
rectangle.rs

1use crate::alignment;
2use crate::{Padding, Point, Radians, Size, Vector};
3
4/// An axis-aligned rectangle.
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
6pub struct Rectangle<T = f32> {
7    /// X coordinate of the top-left corner.
8    pub x: T,
9
10    /// Y coordinate of the top-left corner.
11    pub y: T,
12
13    /// Width of the rectangle.
14    pub width: T,
15
16    /// Height of the rectangle.
17    pub height: T,
18}
19
20impl<T> Rectangle<T>
21where
22    T: Default,
23{
24    /// Creates a new [`Rectangle`] with its top-left corner at the origin
25    /// and with the provided [`Size`].
26    pub fn with_size(size: Size<T>) -> Self {
27        Self {
28            x: T::default(),
29            y: T::default(),
30            width: size.width,
31            height: size.height,
32        }
33    }
34}
35
36impl Rectangle<f32> {
37    /// A rectangle starting at [`Point::ORIGIN`] with infinite width and height.
38    pub const INFINITE: Self = Self::new(Point::ORIGIN, Size::INFINITY);
39
40    /// Creates a new [`Rectangle`] with its top-left corner in the given
41    /// [`Point`] and with the provided [`Size`].
42    pub const fn new(top_left: Point, size: Size) -> Self {
43        Self {
44            x: top_left.x,
45            y: top_left.y,
46            width: size.width,
47            height: size.height,
48        }
49    }
50
51    /// Creates a new square [`Rectangle`] with the center at the origin and
52    /// with the given radius.
53    pub fn with_radius(radius: f32) -> Self {
54        Self {
55            x: -radius,
56            y: -radius,
57            width: radius * 2.0,
58            height: radius * 2.0,
59        }
60    }
61
62    /// Creates a new axis-aligned [`Rectangle`] from the given vertices; returning the
63    /// rotation in [`Radians`] that must be applied to the axis-aligned [`Rectangle`]
64    /// to obtain the desired result.
65    pub fn with_vertices(
66        top_left: Point,
67        top_right: Point,
68        bottom_left: Point,
69    ) -> (Rectangle, Radians) {
70        let width = (top_right.x - top_left.x).hypot(top_right.y - top_left.y);
71
72        let height =
73            (bottom_left.x - top_left.x).hypot(bottom_left.y - top_left.y);
74
75        let rotation =
76            (top_right.y - top_left.y).atan2(top_right.x - top_left.x);
77
78        let rotation = if rotation < 0.0 {
79            2.0 * std::f32::consts::PI + rotation
80        } else {
81            rotation
82        };
83
84        let position = {
85            let center = Point::new(
86                (top_right.x + bottom_left.x) / 2.0,
87                (top_right.y + bottom_left.y) / 2.0,
88            );
89
90            let rotation = -rotation - std::f32::consts::PI * 2.0;
91
92            Point::new(
93                center.x + (top_left.x - center.x) * rotation.cos()
94                    - (top_left.y - center.y) * rotation.sin(),
95                center.y
96                    + (top_left.x - center.x) * rotation.sin()
97                    + (top_left.y - center.y) * rotation.cos(),
98            )
99        };
100
101        (
102            Rectangle::new(position, Size::new(width, height)),
103            Radians(rotation),
104        )
105    }
106
107    /// Returns the [`Point`] at the center of the [`Rectangle`].
108    pub fn center(&self) -> Point {
109        Point::new(self.center_x(), self.center_y())
110    }
111
112    /// Returns the X coordinate of the [`Point`] at the center of the
113    /// [`Rectangle`].
114    pub fn center_x(&self) -> f32 {
115        self.x + self.width / 2.0
116    }
117
118    /// Returns the Y coordinate of the [`Point`] at the center of the
119    /// [`Rectangle`].
120    pub fn center_y(&self) -> f32 {
121        self.y + self.height / 2.0
122    }
123
124    /// Returns the position of the top left corner of the [`Rectangle`].
125    pub fn position(&self) -> Point {
126        Point::new(self.x, self.y)
127    }
128
129    /// Returns the [`Size`] of the [`Rectangle`].
130    pub fn size(&self) -> Size {
131        Size::new(self.width, self.height)
132    }
133
134    /// Returns the area of the [`Rectangle`].
135    pub fn area(&self) -> f32 {
136        self.width * self.height
137    }
138
139    /// Returns true if the given [`Point`] is contained in the [`Rectangle`].
140    pub fn contains(&self, point: Point) -> bool {
141        self.x <= point.x
142            && point.x < self.x + self.width
143            && self.y <= point.y
144            && point.y < self.y + self.height
145    }
146
147    /// Returns the minimum distance from the given [`Point`] to any of the edges
148    /// of the [`Rectangle`].
149    pub fn distance(&self, point: Point) -> f32 {
150        let center = self.center();
151
152        let distance_x =
153            ((point.x - center.x).abs() - self.width / 2.0).max(0.0);
154
155        let distance_y =
156            ((point.y - center.y).abs() - self.height / 2.0).max(0.0);
157
158        distance_x.hypot(distance_y)
159    }
160
161    /// Computes the offset that must be applied to the [`Rectangle`] to be placed
162    /// inside the given `container`.
163    pub fn offset(&self, container: &Rectangle) -> Vector {
164        let Some(intersection) = self.intersection(container) else {
165            return Vector::ZERO;
166        };
167
168        let left = intersection.x - self.x;
169        let top = intersection.y - self.y;
170
171        Vector::new(
172            if left > 0.0 {
173                left
174            } else {
175                intersection.x + intersection.width - self.x - self.width
176            },
177            if top > 0.0 {
178                top
179            } else {
180                intersection.y + intersection.height - self.y - self.height
181            },
182        )
183    }
184
185    /// Returns true if the current [`Rectangle`] is completely within the given
186    /// `container`.
187    pub fn is_within(&self, container: &Rectangle) -> bool {
188        container.contains(self.position())
189            && container.contains(
190                self.position() + Vector::new(self.width, self.height),
191            )
192    }
193
194    /// Computes the intersection with the given [`Rectangle`].
195    pub fn intersection(
196        &self,
197        other: &Rectangle<f32>,
198    ) -> Option<Rectangle<f32>> {
199        let x = self.x.max(other.x);
200        let y = self.y.max(other.y);
201
202        let lower_right_x = (self.x + self.width).min(other.x + other.width);
203        let lower_right_y = (self.y + self.height).min(other.y + other.height);
204
205        let width = lower_right_x - x;
206        let height = lower_right_y - y;
207
208        if width > 0.0 && height > 0.0 {
209            Some(Rectangle {
210                x,
211                y,
212                width,
213                height,
214            })
215        } else {
216            None
217        }
218    }
219
220    /// Returns whether the [`Rectangle`] intersects with the given one.
221    pub fn intersects(&self, other: &Self) -> bool {
222        self.intersection(other).is_some()
223    }
224
225    /// Computes the union with the given [`Rectangle`].
226    pub fn union(&self, other: &Self) -> Self {
227        let x = self.x.min(other.x);
228        let y = self.y.min(other.y);
229
230        let lower_right_x = (self.x + self.width).max(other.x + other.width);
231        let lower_right_y = (self.y + self.height).max(other.y + other.height);
232
233        let width = lower_right_x - x;
234        let height = lower_right_y - y;
235
236        Rectangle {
237            x,
238            y,
239            width,
240            height,
241        }
242    }
243
244    /// Snaps the [`Rectangle`] to __unsigned__ integer coordinates.
245    pub fn snap(self) -> Option<Rectangle<u32>> {
246        let width = self.width as u32;
247        let height = self.height as u32;
248
249        if width < 1 || height < 1 {
250            return None;
251        }
252
253        Some(Rectangle {
254            x: self.x as u32,
255            y: self.y as u32,
256            width,
257            height,
258        })
259    }
260
261    /// Expands the [`Rectangle`] a given amount.
262    pub fn expand(self, padding: impl Into<Padding>) -> Self {
263        let padding = padding.into();
264
265        Self {
266            x: self.x - padding.left,
267            y: self.y - padding.top,
268            width: self.width + padding.horizontal(),
269            height: self.height + padding.vertical(),
270        }
271    }
272
273    /// Shrinks the [`Rectangle`] a given amount.
274    pub fn shrink(self, padding: impl Into<Padding>) -> Self {
275        let padding = padding.into();
276
277        Self {
278            x: self.x + padding.left,
279            y: self.y + padding.top,
280            width: self.width - padding.horizontal(),
281            height: self.height - padding.vertical(),
282        }
283    }
284
285    /// Rotates the [`Rectangle`] and returns the smallest [`Rectangle`]
286    /// containing it.
287    pub fn rotate(self, rotation: Radians) -> Self {
288        let size = self.size().rotate(rotation);
289        let position = Point::new(
290            self.center_x() - size.width / 2.0,
291            self.center_y() - size.height / 2.0,
292        );
293
294        Self::new(position, size)
295    }
296
297    /// Scales the [`Rectangle`] without changing its position, effectively
298    /// "zooming" it.
299    pub fn zoom(self, zoom: f32) -> Self {
300        Self {
301            x: self.x - (self.width * (zoom - 1.0)) / 2.0,
302            y: self.y - (self.height * (zoom - 1.0)) / 2.0,
303            width: self.width * zoom,
304            height: self.height * zoom,
305        }
306    }
307
308    /// Returns the top-left position to render an object of the given [`Size`].
309    /// inside the [`Rectangle`] that is anchored to the edge or corner
310    /// defined by the alignment arguments.
311    pub fn anchor(
312        &self,
313        size: Size,
314        align_x: impl Into<alignment::Horizontal>,
315        align_y: impl Into<alignment::Vertical>,
316    ) -> Point {
317        let x = match align_x.into() {
318            alignment::Horizontal::Left => self.x,
319            alignment::Horizontal::Center => {
320                self.x + (self.width - size.width) / 2.0
321            }
322            alignment::Horizontal::Right => self.x + self.width - size.width,
323        };
324
325        let y = match align_y.into() {
326            alignment::Vertical::Top => self.y,
327            alignment::Vertical::Center => {
328                self.y + (self.height - size.height) / 2.0
329            }
330            alignment::Vertical::Bottom => self.y + self.height - size.height,
331        };
332
333        Point::new(x, y)
334    }
335}
336
337impl std::ops::Mul<f32> for Rectangle<f32> {
338    type Output = Self;
339
340    fn mul(self, scale: f32) -> Self {
341        Self {
342            x: self.x * scale,
343            y: self.y * scale,
344            width: self.width * scale,
345            height: self.height * scale,
346        }
347    }
348}
349
350impl From<Rectangle<u32>> for Rectangle<f32> {
351    fn from(rectangle: Rectangle<u32>) -> Rectangle<f32> {
352        Rectangle {
353            x: rectangle.x as f32,
354            y: rectangle.y as f32,
355            width: rectangle.width as f32,
356            height: rectangle.height as f32,
357        }
358    }
359}
360
361impl<T> std::ops::Add<Vector<T>> for Rectangle<T>
362where
363    T: std::ops::Add<Output = T>,
364{
365    type Output = Rectangle<T>;
366
367    fn add(self, translation: Vector<T>) -> Self {
368        Rectangle {
369            x: self.x + translation.x,
370            y: self.y + translation.y,
371            ..self
372        }
373    }
374}
375
376impl<T> std::ops::Sub<Vector<T>> for Rectangle<T>
377where
378    T: std::ops::Sub<Output = T>,
379{
380    type Output = Rectangle<T>;
381
382    fn sub(self, translation: Vector<T>) -> Self {
383        Rectangle {
384            x: self.x - translation.x,
385            y: self.y - translation.y,
386            ..self
387        }
388    }
389}
390
391impl<T> std::ops::Mul<Vector<T>> for Rectangle<T>
392where
393    T: std::ops::Mul<Output = T> + Copy,
394{
395    type Output = Rectangle<T>;
396
397    fn mul(self, scale: Vector<T>) -> Self {
398        Rectangle {
399            x: self.x * scale.x,
400            y: self.y * scale.y,
401            width: self.width * scale.x,
402            height: self.height * scale.y,
403        }
404    }
405}