iced_graphics/geometry/
text.rs

1use crate::core;
2use crate::core::alignment;
3use crate::core::text::{Alignment, LineHeight, Paragraph, Shaping, Wrapping};
4use crate::core::{Color, Font, Pixels, Point, Size, Vector};
5use crate::geometry::Path;
6use crate::text;
7
8/// A bunch of text that can be drawn to a canvas
9#[derive(Debug, Clone)]
10pub struct Text {
11    /// The contents of the text
12    pub content: String,
13    /// The position of the text relative to the alignment properties.
14    ///
15    /// By default, this position will be relative to the top-left corner coordinate meaning that
16    /// if the horizontal and vertical alignments are unchanged, this property will tell where the
17    /// top-left corner of the text should be placed.
18    ///
19    /// By changing the horizontal_alignment and vertical_alignment properties, you are are able to
20    /// change what part of text is placed at this positions.
21    ///
22    /// For example, when the horizontal_alignment and vertical_alignment are set to Center, the
23    /// center of the text will be placed at the given position NOT the top-left coordinate.
24    pub position: Point,
25    /// The maximum horizontal space available for this [`Text`].
26    ///
27    /// Text will break into new lines when the width is reached.
28    pub max_width: f32,
29    /// The color of the text
30    pub color: Color,
31    /// The size of the text
32    pub size: Pixels,
33    /// The line height of the text.
34    pub line_height: LineHeight,
35    /// The font of the text
36    pub font: Font,
37    /// The horizontal alignment of the text
38    pub align_x: Alignment,
39    /// The vertical alignment of the text
40    pub align_y: alignment::Vertical,
41    /// The shaping strategy of the text.
42    pub shaping: Shaping,
43}
44
45impl Text {
46    /// Computes the [`Path`]s of the [`Text`] and draws them using
47    /// the given closure.
48    pub fn draw_with(&self, mut f: impl FnMut(Path, Color)) {
49        let paragraph = text::Paragraph::with_text(core::text::Text {
50            content: &self.content,
51            bounds: Size::new(self.max_width, f32::INFINITY),
52            size: self.size,
53            line_height: self.line_height,
54            font: self.font,
55            align_x: self.align_x,
56            align_y: self.align_y,
57            shaping: self.shaping,
58            wrapping: Wrapping::default(),
59        });
60
61        let translation_x = match self.align_x {
62            Alignment::Default | Alignment::Left | Alignment::Justified => self.position.x,
63            Alignment::Center => self.position.x - paragraph.min_width() / 2.0,
64            Alignment::Right => self.position.x - paragraph.min_width(),
65        };
66
67        let translation_y = {
68            match self.align_y {
69                alignment::Vertical::Top => self.position.y,
70                alignment::Vertical::Center => self.position.y - paragraph.min_height() / 2.0,
71                alignment::Vertical::Bottom => self.position.y - paragraph.min_height(),
72            }
73        };
74
75        let buffer = paragraph.buffer();
76        let mut swash_cache = cosmic_text::SwashCache::new();
77
78        let mut font_system = text::font_system().write().expect("Write font system");
79
80        for run in buffer.layout_runs() {
81            for glyph in run.glyphs.iter() {
82                let physical_glyph = glyph.physical((0.0, 0.0), 1.0);
83
84                let start_x = translation_x + glyph.x + glyph.x_offset;
85                let start_y = translation_y + glyph.y_offset + run.line_y;
86                let offset = Vector::new(start_x, start_y);
87
88                if let Some(commands) =
89                    swash_cache.get_outline_commands(font_system.raw(), physical_glyph.cache_key)
90                {
91                    let glyph = Path::new(|path| {
92                        use cosmic_text::Command;
93
94                        for command in commands {
95                            match command {
96                                Command::MoveTo(p) => {
97                                    path.move_to(Point::new(p.x, -p.y) + offset);
98                                }
99                                Command::LineTo(p) => {
100                                    path.line_to(Point::new(p.x, -p.y) + offset);
101                                }
102                                Command::CurveTo(control_a, control_b, to) => {
103                                    path.bezier_curve_to(
104                                        Point::new(control_a.x, -control_a.y) + offset,
105                                        Point::new(control_b.x, -control_b.y) + offset,
106                                        Point::new(to.x, -to.y) + offset,
107                                    );
108                                }
109                                Command::QuadTo(control, to) => {
110                                    path.quadratic_curve_to(
111                                        Point::new(control.x, -control.y) + offset,
112                                        Point::new(to.x, -to.y) + offset,
113                                    );
114                                }
115                                Command::Close => {
116                                    path.close();
117                                }
118                            }
119                        }
120                    });
121
122                    f(glyph, self.color);
123                } else {
124                    // TODO: Raster image support for `Canvas`
125                    let [r, g, b, a] = self.color.into_rgba8();
126
127                    swash_cache.with_pixels(
128                        font_system.raw(),
129                        physical_glyph.cache_key,
130                        cosmic_text::Color::rgba(r, g, b, a),
131                        |x, y, color| {
132                            f(
133                                Path::rectangle(
134                                    Point::new(x as f32, y as f32) + offset,
135                                    Size::new(1.0, 1.0),
136                                ),
137                                Color::from_rgba8(
138                                    color.r(),
139                                    color.g(),
140                                    color.b(),
141                                    color.a() as f32 / 255.0,
142                                ),
143                            );
144                        },
145                    );
146                }
147            }
148        }
149    }
150}
151
152impl Default for Text {
153    fn default() -> Text {
154        Text {
155            content: String::new(),
156            position: Point::ORIGIN,
157            max_width: f32::INFINITY,
158            color: Color::BLACK,
159            size: Pixels(16.0),
160            line_height: LineHeight::Relative(1.2),
161            font: Font::default(),
162            align_x: Alignment::Default,
163            align_y: alignment::Vertical::Top,
164            shaping: Shaping::default(),
165        }
166    }
167}
168
169impl From<String> for Text {
170    fn from(content: String) -> Text {
171        Text {
172            content,
173            ..Default::default()
174        }
175    }
176}
177
178impl From<&str> for Text {
179    fn from(content: &str) -> Text {
180        String::from(content).into()
181    }
182}