From 8cce09687f533409d00c4c35c506ea6a735b59a6 Mon Sep 17 00:00:00 2001 From: Emil Ernerfeldt Date: Thu, 20 May 2021 21:53:39 +0200 Subject: [PATCH] Expose text layout functions in Painter --- egui/src/painter.rs | 36 ++++++++++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/egui/src/painter.rs b/egui/src/painter.rs index 9a2c9ce8..f8d4fb5d 100644 --- a/egui/src/painter.rs +++ b/egui/src/painter.rs @@ -299,6 +299,9 @@ impl Painter { /// /// To center the text at the given position, use `anchor: (Center, Center)`. /// + /// To find out the size of text before painting it, use + /// [`Self::layout_no_wrap`] or [`Self::layout_multiline`]. + /// /// Returns where the text ended up. #[allow(clippy::needless_pass_by_value)] pub fn text( @@ -309,15 +312,40 @@ impl Painter { text_style: TextStyle, text_color: Color32, ) -> Rect { - let galley = self - .fonts() - .layout_multiline(text_style, text.to_string(), f32::INFINITY); + let galley = self.layout_no_wrap(text_style, text.to_string()); let rect = anchor.anchor_rect(Rect::from_min_size(pos, galley.size)); self.galley(rect.min, galley, text_color); rect } - /// Paint text that has already been layed out in a `Galley`. + /// Will line break at `\n`. + /// + /// Paint the results with [`Self::galley`]. + /// Always returns at least one row. + #[inline(always)] + pub fn layout_no_wrap(&self, text_style: TextStyle, text: String) -> std::sync::Arc { + self.layout_multiline(text_style, text, f32::INFINITY) + } + + /// Will wrap text at the given width and line break at `\n`. + /// + /// Paint the results with [`Self::galley`]. + /// Always returns at least one row. + #[inline(always)] + pub fn layout_multiline( + &self, + text_style: TextStyle, + text: String, + max_width_in_points: f32, + ) -> std::sync::Arc { + self.fonts() + .layout_multiline(text_style, text, max_width_in_points) + } + + /// Paint text that has already been layed out in a [`Galley`]. + /// + /// You can create the `Galley` with [`Self::layout_no_wrap`] or [`Self::layout_multiline`]. + #[inline(always)] pub fn galley(&self, pos: Pos2, galley: std::sync::Arc, color: Color32) { self.galley_with_italics(pos, galley, color, false) }