cranpose_ui_graphics/
unit.rs1#[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#[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#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
33pub struct Px(pub f32);
34
35#[cfg(test)]
36mod tests {
37 use super::*;
38
39 #[test]
40 fn density_independent_pixels_round_trip_through_a_density() {
41 for density in [1.0f32, 1.5, 2.0, 3.0] {
42 let dp = Dp(24.0);
43 assert_eq!(dp.to_px(density), 24.0 * density);
44 assert_eq!(Dp::from_px(dp.to_px(density), density), dp);
45 }
46 }
47
48 #[test]
49 fn scale_independent_pixels_round_trip_through_density_and_font_scale() {
50 for density in [1.0f32, 2.0, 3.0] {
51 for font_scale in [0.85f32, 1.0, 1.3] {
52 let sp = Sp(16.0);
53 assert_eq!(sp.to_px(density, font_scale), 16.0 * density * font_scale);
54 assert_eq!(
55 Sp::from_px(sp.to_px(density, font_scale), density, font_scale),
56 sp
57 );
58 }
59 }
60 }
61}