embedded_graphics/text/
text_style.rs1use crate::text::{Alignment, Baseline, LineHeight};
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
11#[cfg_attr(feature = "defmt", derive(::defmt::Format))]
12#[non_exhaustive]
13pub struct TextStyle {
14 pub alignment: Alignment,
16
17 pub baseline: Baseline,
19
20 pub line_height: LineHeight,
22}
23
24impl TextStyle {
25 pub const fn with_baseline(baseline: Baseline) -> Self {
27 TextStyleBuilder::new().baseline(baseline).build()
28 }
29
30 pub const fn with_alignment(alignment: Alignment) -> Self {
32 TextStyleBuilder::new().alignment(alignment).build()
33 }
34}
35
36impl Default for TextStyle {
37 fn default() -> Self {
38 TextStyleBuilder::new().build()
39 }
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
44#[cfg_attr(feature = "defmt", derive(::defmt::Format))]
45pub struct TextStyleBuilder {
46 style: TextStyle,
47}
48
49impl TextStyleBuilder {
50 pub const fn new() -> Self {
52 Self {
53 style: TextStyle {
54 alignment: Alignment::Left,
55 baseline: Baseline::Alphabetic,
56 line_height: LineHeight::Percent(100),
57 },
58 }
59 }
60}
61
62impl TextStyleBuilder {
63 pub const fn alignment(mut self, alignment: Alignment) -> Self {
65 self.style.alignment = alignment;
66
67 self
68 }
69
70 pub const fn baseline(mut self, baseline: Baseline) -> Self {
72 self.style.baseline = baseline;
73
74 self
75 }
76
77 pub const fn line_height(mut self, line_height: LineHeight) -> Self {
79 self.style.line_height = line_height;
80
81 self
82 }
83
84 pub const fn build(self) -> TextStyle {
86 self.style
87 }
88}
89
90impl From<&TextStyle> for TextStyleBuilder {
91 fn from(style: &TextStyle) -> Self {
92 Self { style: *style }
93 }
94}
95
96#[cfg(test)]
97mod tests {
98 use super::*;
99
100 #[test]
101 fn builder() {
102 let text_style = TextStyleBuilder::new()
103 .alignment(Alignment::Right)
104 .baseline(Baseline::Top)
105 .line_height(LineHeight::Pixels(123))
106 .build();
107
108 assert_eq!(text_style.alignment, Alignment::Right);
109 assert_eq!(text_style.baseline, Baseline::Top);
110 assert_eq!(text_style.line_height, LineHeight::Pixels(123));
111 }
112
113 #[test]
114 fn builder_default() {
115 let text_style = TextStyleBuilder::new().build();
116
117 assert_eq!(text_style.alignment, Alignment::Left);
118 assert_eq!(text_style.baseline, Baseline::Alphabetic);
119 assert_eq!(text_style.line_height, LineHeight::Percent(100));
120 }
121}