rust_droid/common/
relative_rect.rs

1// src/common/relative_rect.rs
2
3use super::rect::Rect;
4
5/// 使用相对坐标 (0.0 to 1.0) 定义一个矩形区域,以适应不同分辨率的设备。
6#[derive(Debug, Clone, Copy)]
7pub struct RelativeRect {
8    pub x: f32,
9    pub y: f32,
10    pub width: f32,
11    pub height: f32,
12}
13
14impl RelativeRect {
15    /// 创建一个新的相对矩形。
16    ///
17    /// # Panics
18    /// 如果任何值不在 [0.0, 1.0] 范围内,将在 debug 模式下 panic。
19    pub fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
20        debug_assert!((0.0..=1.0).contains(&x));
21        debug_assert!((0.0..=1.0).contains(&y));
22        debug_assert!((0.0..=1.0).contains(&width));
23        debug_assert!((0.0..=1.0).contains(&height));
24        Self {
25            x,
26            y,
27            width,
28            height,
29        }
30    }
31
32    /// 将相对矩形转换为基于屏幕尺寸的绝对像素矩形。
33    pub fn to_absolute(&self, screen_width: u32, screen_height: u32) -> Rect {
34        Rect {
35            x: (self.x * screen_width as f32) as u32,
36            y: (self.y * screen_height as f32) as u32,
37            width: (self.width * screen_width as f32) as u32,
38            height: (self.height * screen_height as f32) as u32,
39        }
40    }
41}