geng_ui/widgets/
string.rs

1use super::*;
2
3const TEXT_ALIGN: vec2<TextAlign> = vec2(TextAlign::LEFT, TextAlign::LEFT);
4
5pub(crate) fn calc_text_constraints(
6    text: &str,
7    font: &Font,
8    size: f32,
9    _cx: &ConstraintsContext,
10) -> Constraints {
11    Constraints {
12        min_size: vec2(
13            font.measure(text, TEXT_ALIGN)
14                .map_or(0.0, |aabb| aabb.width() as f64),
15            1.0,
16        ) * size as f64,
17        flex: vec2(0.0, 0.0),
18    }
19}
20
21pub(crate) fn draw_text(text: &str, font: &Font, color: Rgba<f32>, cx: &mut DrawContext) {
22    if text.is_empty() {
23        return;
24    }
25    let _size = partial_min(
26        cx.position.height() as f32,
27        cx.position.width() as f32
28            / font
29                .measure(text, TEXT_ALIGN)
30                .map_or(0.0, |aabb| aabb.width()),
31    );
32    let size = cx.position.height() as f32;
33    font.draw(
34        cx.framebuffer,
35        &PixelPerfectCamera,
36        text,
37        TEXT_ALIGN,
38        mat3::translate(
39            cx.position.bottom_left().map(|x| x as f32) + vec2(0.0, -font.descender() * size),
40        ) * mat3::scale_uniform(size),
41        color,
42    );
43}
44
45impl Widget for String {
46    fn calc_constraints(&mut self, cx: &ConstraintsContext) -> Constraints {
47        calc_text_constraints(self.as_str(), &cx.theme.font, cx.theme.text_size, cx)
48    }
49    fn draw(&mut self, cx: &mut DrawContext) {
50        draw_text(self.as_str(), &cx.theme.font, cx.theme.text_color, cx);
51    }
52}
53
54impl Widget for &'_ str {
55    fn calc_constraints(&mut self, cx: &ConstraintsContext) -> Constraints {
56        calc_text_constraints(self, &cx.theme.font, cx.theme.text_size, cx)
57    }
58    fn draw(&mut self, cx: &mut DrawContext) {
59        draw_text(self, &cx.theme.font, cx.theme.text_color, cx);
60    }
61}