From a15040c01183421935ba7dd72fc1ac5880d55dff Mon Sep 17 00:00:00 2001 From: Patrick Marks Date: Sun, 18 May 2025 19:19:12 +0200 Subject: [PATCH] Fix `visual_bounding_rect` for rotated text (#7050) TextShape.visual_bounding_rect was not taking the text rotation into account. I manually tested drawing the new bounding box on top of the text for various rotations & anchor settings. For example: image The unit test I added will fail without this patch, but perhaps doesn't add much value. * [x] I have followed the instructions in the PR template --- crates/epaint/src/shapes/text_shape.rs | 40 +++++++++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/crates/epaint/src/shapes/text_shape.rs b/crates/epaint/src/shapes/text_shape.rs index e88213b9..4ea0ac35 100644 --- a/crates/epaint/src/shapes/text_shape.rs +++ b/crates/epaint/src/shapes/text_shape.rs @@ -59,7 +59,10 @@ impl TextShape { /// The visual bounding rectangle #[inline] pub fn visual_bounding_rect(&self) -> Rect { - self.galley.mesh_bounds.translate(self.pos.to_vec2()) + self.galley + .mesh_bounds + .rotate_bb(emath::Rot2::from_angle(self.angle)) + .translate(self.pos.to_vec2()) } #[inline] @@ -154,3 +157,38 @@ impl From for Shape { Self::Text(shape) } } + +#[cfg(test)] +mod tests { + use super::{super::*, *}; + use crate::text::FontDefinitions; + use emath::almost_equal; + + #[test] + fn text_bounding_box_under_rotation() { + let fonts = Fonts::new(1.0, 1024, FontDefinitions::default()); + let font = FontId::monospace(12.0); + + let mut t = crate::Shape::text( + &fonts, + Pos2::ZERO, + emath::Align2::CENTER_CENTER, + "testing123", + font, + Color32::BLACK, + ); + + let size_orig = t.visual_bounding_rect().size(); + + // 90 degree rotation + if let Shape::Text(ts) = &mut t { + ts.angle = std::f32::consts::PI / 2.0; + } + + let size_rot = t.visual_bounding_rect().size(); + + // make sure the box is actually rotated + assert!(almost_equal(size_orig.x, size_rot.y, 1e-4)); + assert!(almost_equal(size_orig.y, size_rot.x, 1e-4)); + } +}