cranpose_ui_layout/
alignment.rs1use crate::round_to_px;
4
5pub fn bias_offset(bias: f32, available: f32, child: f32, density: f32) -> f32 {
10 round_to_px((available - child) / 2.0 * (1.0 + bias), density)
11}
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub struct Alignment {
16 pub horizontal: HorizontalAlignment,
18 pub vertical: VerticalAlignment,
20}
21
22impl Alignment {
23 pub const fn new(horizontal: HorizontalAlignment, vertical: VerticalAlignment) -> Self {
25 Self {
26 horizontal,
27 vertical,
28 }
29 }
30
31 pub const TOP_START: Self = Self::new(HorizontalAlignment::Start, VerticalAlignment::Top);
33
34 pub const TOP_CENTER: Self = Self::new(
36 HorizontalAlignment::CenterHorizontally,
37 VerticalAlignment::Top,
38 );
39
40 pub const TOP_END: Self = Self::new(HorizontalAlignment::End, VerticalAlignment::Top);
42
43 pub const CENTER_START: Self = Self::new(
45 HorizontalAlignment::Start,
46 VerticalAlignment::CenterVertically,
47 );
48
49 pub const CENTER: Self = Self::new(
51 HorizontalAlignment::CenterHorizontally,
52 VerticalAlignment::CenterVertically,
53 );
54
55 pub const CENTER_END: Self = Self::new(
57 HorizontalAlignment::End,
58 VerticalAlignment::CenterVertically,
59 );
60
61 pub const BOTTOM_START: Self = Self::new(HorizontalAlignment::Start, VerticalAlignment::Bottom);
63
64 pub const BOTTOM_CENTER: Self = Self::new(
66 HorizontalAlignment::CenterHorizontally,
67 VerticalAlignment::Bottom,
68 );
69
70 pub const BOTTOM_END: Self = Self::new(HorizontalAlignment::End, VerticalAlignment::Bottom);
72}
73
74#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub enum HorizontalAlignment {
77 Start,
79 CenterHorizontally,
81 End,
83}
84
85impl HorizontalAlignment {
86 pub fn bias(&self) -> f32 {
88 match self {
89 HorizontalAlignment::Start => -1.0,
90 HorizontalAlignment::CenterHorizontally => 0.0,
91 HorizontalAlignment::End => 1.0,
92 }
93 }
94
95 pub fn align(&self, available: f32, child: f32, density: f32) -> f32 {
98 bias_offset(self.bias(), available, child, density)
99 }
100}
101
102#[derive(Clone, Copy, Debug, PartialEq, Eq)]
104pub enum VerticalAlignment {
105 Top,
107 CenterVertically,
109 Bottom,
111}
112
113impl VerticalAlignment {
114 pub fn bias(&self) -> f32 {
116 match self {
117 VerticalAlignment::Top => -1.0,
118 VerticalAlignment::CenterVertically => 0.0,
119 VerticalAlignment::Bottom => 1.0,
120 }
121 }
122
123 pub fn align(&self, available: f32, child: f32, density: f32) -> f32 {
126 bias_offset(self.bias(), available, child, density)
127 }
128}
129
130#[cfg(test)]
131#[path = "tests/alignment_tests.rs"]
132mod tests;