Add `Align2::anchor_size` (#3863)

This commit is contained in:
Emil Ernerfeldt 2024-01-22 16:47:50 +01:00 committed by GitHub
parent 9fb83d3541
commit 31cc31a67b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 21 additions and 6 deletions

View File

@ -229,7 +229,7 @@ impl Painter {
text: impl ToString,
) -> Rect {
let galley = self.layout_no_wrap(text.to_string(), FontId::monospace(12.0), color);
let rect = anchor.anchor_rect(Rect::from_min_size(pos, galley.size()));
let rect = anchor.anchor_size(pos, galley.size());
let frame_rect = rect.expand(2.0);
self.add(Shape::rect_filled(
frame_rect,
@ -378,7 +378,7 @@ impl Painter {
text_color: Color32,
) -> Rect {
let galley = self.layout_no_wrap(text.to_string(), font_id, text_color);
let rect = anchor.anchor_rect(Rect::from_min_size(pos, galley.size()));
let rect = anchor.anchor_size(pos, galley.size());
self.galley(rect.min, galley, text_color);
rect
}

View File

@ -728,9 +728,7 @@ impl PlotItem for Text {
.into_galley(ui, Some(false), f32::INFINITY, TextStyle::Small);
let pos = transform.position_from_point(&self.position);
let rect = self
.anchor
.anchor_rect(Rect::from_min_size(pos, galley.size()));
let rect = self.anchor.anchor_size(pos, galley.size());
shapes.push(epaint::TextShape::new(rect.min, galley, color).into());

View File

@ -186,6 +186,23 @@ impl Align2 {
Rect::from_min_size(pos2(x, y), rect.size())
}
/// Use this anchor to position something around `pos`,
/// e.g. [`Self::RIGHT_TOP`] means the right-top of the rect
/// will end up at `pos`.
pub fn anchor_size(self, pos: Pos2, size: Vec2) -> Rect {
let x = match self.x() {
Align::Min => pos.x,
Align::Center => pos.x - 0.5 * size.x,
Align::Max => pos.x - size.x,
};
let y = match self.y() {
Align::Min => pos.y,
Align::Center => pos.y - 0.5 * size.y,
Align::Max => pos.y - size.y,
};
Rect::from_min_size(pos2(x, y), size)
}
/// e.g. center a size within a given frame
pub fn align_size_within_rect(self, size: Vec2, frame: Rect) -> Rect {
let x_range = self.x().align_size_within_range(size.x, frame.x_range());

View File

@ -264,7 +264,7 @@ impl Shape {
color: Color32,
) -> Self {
let galley = fonts.layout_no_wrap(text.to_string(), font_id, color);
let rect = anchor.anchor_rect(Rect::from_min_size(pos, galley.size()));
let rect = anchor.anchor_size(pos, galley.size());
Self::galley(rect.min, galley, color)
}