Skip to main content

cranpose_ui_graphics/
unit.rs

1//! Unit types: Dp, Sp, and conversions
2
3/// Density-independent pixels
4#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
5pub struct Dp(pub f32);
6
7impl Dp {
8    pub fn to_px(&self, density: f32) -> f32 {
9        self.0 * density
10    }
11
12    pub fn from_px(px: f32, density: f32) -> Self {
13        Self(px / density)
14    }
15}
16
17/// Scale-independent pixels (for text)
18#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
19pub struct Sp(pub f32);
20
21impl Sp {
22    pub fn to_px(&self, density: f32, font_scale: f32) -> f32 {
23        self.0 * density * font_scale
24    }
25
26    pub fn from_px(px: f32, density: f32, font_scale: f32) -> Self {
27        Self(px / (density * font_scale))
28    }
29}
30
31/// Raw pixels
32#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
33pub struct Px(pub f32);