From 785d5f005ee3f0b9cbe7409bbce3589bb01e69bc Mon Sep 17 00:00:00 2001 From: tigregalis Date: Sun, 17 Jan 2021 13:15:50 +0800 Subject: [PATCH] updated text example to better document new API --- examples/ui/text.rs | 67 ++++++++++++++++++++++++++++++++++++++------- 1 file changed, 57 insertions(+), 10 deletions(-) diff --git a/examples/ui/text.rs b/examples/ui/text.rs index 26058387488d10..c984dd27abaa75 100644 --- a/examples/ui/text.rs +++ b/examples/ui/text.rs @@ -11,33 +11,55 @@ fn main() { .add_plugin(FrameTimeDiagnosticsPlugin::default()) .add_startup_system(setup.system()) .add_system(text_update_system.system()) + .add_system(text_color_system.system()) .run(); } // A unit struct to help identify the FPS UI component, since there may be many Text components struct FpsText; -fn text_update_system(diagnostics: Res, mut query: Query<&mut Text, With>) { - for mut text in query.iter_mut() { - if let Some(fps) = diagnostics.get(FrameTimeDiagnosticsPlugin::FPS) { - if let Some(average) = fps.average() { - text.sections[1].value = format!("{:.2}", average); - } - } - } -} +// A unit struct to help identify the color-changing Text component +struct ColorText; fn setup(commands: &mut Commands, asset_server: Res) { commands // UI camera .spawn(CameraUiBundle::default()) - // texture + // Text with one section + .spawn(TextBundle { + style: Style { + align_self: AlignSelf::FlexEnd, + position_type: PositionType::Absolute, + position: Rect { + bottom: Val::Px(5.0), + right: Val::Px(15.0), + ..Default::default() + }, + ..Default::default() + }, + // construct a `BasicText` + text: BasicText { + value: "hello bevy!".to_string(), + style: TextStyle { + font: asset_server.load("fonts/FiraSans-Bold.ttf"), + font_size: 100.0, + color: Color::WHITE, + }, + ..Default::default() + } + .into(), // convert it to `Text` + ..Default::default() + }) + .with(ColorText) + // Rich text with multiple sections .spawn(TextBundle { style: Style { align_self: AlignSelf::FlexEnd, ..Default::default() }, + // use `Text` directly text: Text { + // construct a `Vec` of `TextSection`s sections: vec![ TextSection { value: "FPS: ".to_string(), @@ -62,3 +84,28 @@ fn setup(commands: &mut Commands, asset_server: Res) { }) .with(FpsText); } + +fn text_update_system(diagnostics: Res, mut query: Query<&mut Text, With>) { + for mut text in query.iter_mut() { + if let Some(fps) = diagnostics.get(FrameTimeDiagnosticsPlugin::FPS) { + if let Some(average) = fps.average() { + // Update the value of the second section + text.sections[1].value = format!("{:.2}", average); + } + } + } +} + +fn text_color_system(time: Res