-
-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Description
Bevy version
0.9
What you did
Attempted to center word wrapped text.
What went wrong
The text was centered in a space as wide as the longest line, rather than the width of the text node, and then moved to the left side of the text node. This resulted in it being off-center to the left.
Additional information
It appears that TextAlignment first calculates the dimensions of the text itself, ignoring the any size specified on the text node. Then it aligns the text within that box, and puts that box against the top-left of the box of the text node. This means that when there is no word wrap, TextAlignment will do nothing at all, because it will be aligning the text in a box that's exactly the same size as the text.
When there is word wrap, it'll determine the width of the box by the width of the widest line. Then all the shorter lines will be aligned correctly relative to that. However, the longest line will generally still be less wide than the width of the text node, so the extra space will be made up with padding on the right.
The vertical alignment portion effectively never works, presumably for the same reason. The vertical size of the text is calculated, and it's vertically aligned in that space, which doesn't do anything. And then if the text node is taller than that, the extra space is made up with bottom padding.
In this screenshot, the text node's dimensions are the dimensions of the gray rectangle, and it's given a TextAlignment::CENTER
.
The relevant bit of my UI code that produced that screenshot is this:
parent
.spawn(NodeBundle {
style: Style {
size: Size::new(Val::Percent(100.0), Val::Px(180.0)),
padding: UiRect::all(Val::Px(4.0)),
margin: UiRect { top: Val::Px(10.0), ..default() },
flex_direction: FlexDirection::Column,
..default()
},
background_color: BackgroundColor(Color::rgb(0.3, 0.3, 0.3)),
..default()
})
.with_children(|parent| {
parent
.spawn(
TextBundle::from_section(
&scroll.description,
TextStyle {
font: asset_server.load("fonts/FiraSans-Bold.ttf"),
font_size: 20.0,
color: Color::WHITE,
}
)
.with_style(Style {
size: Size::new(Val::Px(272.0), Val::Px(172.0)),
..default()
})
.with_text_alignment(TextAlignment::CENTER)
);
});