xref: /StarryEngine/starry_toolkit/src/base/rect.rs (revision 45e1715779ec63c9948d677df0dab834e236e747)
1 use super::point::Point;
2 
3 /// 表示一个矩形区域
4 #[derive(Clone, Copy, Debug, Default)]
5 pub struct Rect {
6     /// 左上角x坐标
7     pub x: i32,
8     /// 左上角y坐标
9     pub y: i32,
10     /// 矩形宽度
11     pub width: u32,
12     /// 矩形高度
13     pub height: u32,
14 }
15 
16 impl Rect {
17     pub fn new(x: i32, y: i32, width: u32, height: u32) -> Rect {
18         Rect {
19             x: x,
20             y: y,
21             width: width,
22             height: height,
23         }
24     }
25 
26     /// 返回矩形左上角的位置点
27     pub fn point(&self) -> Point {
28         Point::new(self.x, self.y)
29     }
30 
31     /// 判断该矩形是否包含某点
32     pub fn contains(&self, p: Point) -> bool {
33         p.x >= self.x
34             && p.x < self.x + self.width as i32
35             && p.y >= self.y
36             && p.y < self.y + self.height as i32
37     }
38 
39     /// 判断该矩形是否完全包含另一个矩形
40     pub fn contains_rect(&self, r: &Rect) -> bool {
41         let p1 = r.point();
42         let p2 = p1 + Point::new(r.width as i32, r.height as i32);
43         self.contains(p1) && self.contains(p2)
44     }
45 
46     // 判断该矩形是否和另一矩形有重叠部分
47     pub fn intersects(&self, r: &Rect) -> bool {
48         !(r.x >= (self.x + self.width as i32)
49             || self.x >= (r.x + r.width as i32)
50             || r.y >= (self.y + self.height as i32)
51             || self.y >= (r.y + r.height as i32))
52     }
53 }
54