Expose text layout functions in Painter

This commit is contained in:
Emil Ernerfeldt 2021-05-20 21:53:39 +02:00
parent 53d5d32a80
commit 8cce09687f

View file

@ -299,6 +299,9 @@ impl Painter {
/// ///
/// To center the text at the given position, use `anchor: (Center, Center)`. /// 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. /// Returns where the text ended up.
#[allow(clippy::needless_pass_by_value)] #[allow(clippy::needless_pass_by_value)]
pub fn text( pub fn text(
@ -309,15 +312,40 @@ impl Painter {
text_style: TextStyle, text_style: TextStyle,
text_color: Color32, text_color: Color32,
) -> Rect { ) -> Rect {
let galley = self let galley = self.layout_no_wrap(text_style, text.to_string());
.fonts()
.layout_multiline(text_style, text.to_string(), f32::INFINITY);
let rect = anchor.anchor_rect(Rect::from_min_size(pos, galley.size)); let rect = anchor.anchor_rect(Rect::from_min_size(pos, galley.size));
self.galley(rect.min, galley, text_color); self.galley(rect.min, galley, text_color);
rect 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<Galley> {
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<Galley> {
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<Galley>, color: Color32) { pub fn galley(&self, pos: Pos2, galley: std::sync::Arc<Galley>, color: Color32) {
self.galley_with_italics(pos, galley, color, false) self.galley_with_italics(pos, galley, color, false)
} }