pub struct TextBundle {
Show 14 fields pub node: Node, pub style: Style, pub text: Text, pub text_layout_info: TextLayoutInfo, pub text_flags: TextFlags, pub calculated_size: ContentSize, pub focus_policy: FocusPolicy, pub transform: Transform, pub global_transform: GlobalTransform, pub visibility: Visibility, pub inherited_visibility: InheritedVisibility, pub view_visibility: ViewVisibility, pub z_index: ZIndex, pub background_color: BackgroundColor,
}
Expand description

A UI node that is text

The positioning of this node is controlled by the UI layout system. If you need manual control, use Text2dBundle.

Fields§

§node: Node

Describes the logical size of the node

§style: Style

Styles which control the layout (size and position) of the node and it’s children In some cases these styles also affect how the node drawn/painted.

§text: Text

Contains the text of the node

§text_layout_info: TextLayoutInfo

Text layout information

§text_flags: TextFlags

Text system flags

§calculated_size: ContentSize

The calculated size based on the given image

§focus_policy: FocusPolicy

Whether this node should block interaction with lower nodes

§transform: Transform

The transform of the node

This component is automatically managed by the UI layout system. To alter the position of the TextBundle, use the properties of the Style component.

§global_transform: GlobalTransform

The global transform of the node

This component is automatically updated by the TransformPropagate systems.

§visibility: Visibility

Describes the visibility properties of the node

§inherited_visibility: InheritedVisibility

Inherited visibility of an entity.

§view_visibility: ViewVisibility

Algorithmically-computed indication of whether an entity is visible and should be extracted for rendering

§z_index: ZIndex

Indicates the depth at which the node should appear in the UI

§background_color: BackgroundColor

The background color that will fill the containing node

Implementations§

source§

impl TextBundle

source

pub fn from_section(value: impl Into<String>, style: TextStyle) -> TextBundle

Create a TextBundle from a single section.

See Text::from_section for usage.

Examples found in repository?
examples/stress_tests/many_gizmos.rs (lines 90-96)
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
fn setup(mut commands: Commands) {
    warn!(include_str!("warning_string.txt"));

    commands.spawn(Camera3dBundle {
        transform: Transform::from_xyz(3., 1., 5.).looking_at(Vec3::ZERO, Vec3::Y),
        ..default()
    });

    commands.spawn(TextBundle::from_section(
        "",
        TextStyle {
            font_size: 30.,
            ..default()
        },
    ));
}
More examples
Hide additional examples
examples/3d/fog.rs (lines 127-133)
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
fn setup_instructions(mut commands: Commands) {
    commands.spawn(
        TextBundle::from_section(
            "",
            TextStyle {
                font_size: 20.0,
                ..default()
            },
        )
        .with_style(Style {
            position_type: PositionType::Absolute,
            top: Val::Px(12.0),
            left: Val::Px(12.0),
            ..default()
        }),
    );
}
examples/scene/scene.rs (lines 152-158)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
fn infotext_system(mut commands: Commands) {
    commands.spawn(Camera2dBundle::default());
    commands.spawn(
        TextBundle::from_section(
            "Nothing to see in this window! Check the console output!",
            TextStyle {
                font_size: 50.0,
                ..default()
            },
        )
        .with_style(Style {
            align_self: AlignSelf::FlexEnd,
            ..default()
        }),
    );
}
examples/3d/atmospheric_fog.rs (lines 98-104)
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
fn setup_instructions(mut commands: Commands) {
    commands.spawn(
        TextBundle::from_section(
            "Press Spacebar to Toggle Atmospheric Fog.\nPress S to Toggle Directional Light Fog Influence.",
            TextStyle {
                font_size: 20.0,
                ..default()
            },
        )
        .with_style(Style {
            position_type: PositionType::Absolute,
            bottom: Val::Px(12.0),
            left: Val::Px(12.0),
            ..default()
        }),
    );
}
examples/window/window_resizing.rs (lines 47-53)
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
fn setup_ui(mut cmd: Commands) {
    // Node that fills entire background
    cmd.spawn(NodeBundle {
        style: Style {
            width: Val::Percent(100.),
            ..default()
        },
        ..default()
    })
    .with_children(|root| {
        // Text where we display current resolution
        root.spawn((
            TextBundle::from_section(
                "Resolution",
                TextStyle {
                    font_size: 50.0,
                    ..default()
                },
            ),
            ResolutionText,
        ));
    });
}
examples/2d/2d_gizmos.rs (lines 23-32)
20
21
22
23
24
25
26
27
28
29
30
31
32
33
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
    commands.spawn(Camera2dBundle::default());
    // text
    commands.spawn(TextBundle::from_section(
        "Hold 'Left' or 'Right' to change the line width of straight gizmos\n\
        Hold 'Up' or 'Down' to change the line width of round gizmos\n\
        Press '1' or '2' to toggle the visibility of straight gizmos or round gizmos",
        TextStyle {
            font: asset_server.load("fonts/FiraMono-Medium.ttf"),
            font_size: 24.,
            color: Color::WHITE,
        },
    ));
}
source

pub fn from_sections( sections: impl IntoIterator<Item = TextSection> ) -> TextBundle

Create a TextBundle from a list of sections.

See Text::from_sections for usage.

Examples found in repository?
examples/games/stepping.rs (lines 187-194)
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
fn build_help(mut commands: Commands, asset_server: Res<AssetServer>) {
    // stepping description box
    commands.spawn((TextBundle::from_sections([TextSection::new(
        "Press ` to toggle stepping mode (S: step system, Space: step frame)",
        TextStyle {
            font: asset_server.load(FONT_MEDIUM),
            font_size: 18.0,
            color: FONT_COLOR,
        },
    )])
    .with_style(Style {
        position_type: PositionType::Absolute,
        bottom: Val::Px(5.0),
        left: Val::Px(5.0),
        ..default()
    }),));
}
More examples
Hide additional examples
examples/games/contributors.rs (lines 146-160)
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
    commands.spawn(Camera2dBundle::default());

    commands.spawn((
        TextBundle::from_sections([
            TextSection::new(
                "Contributor showcase",
                TextStyle {
                    font: asset_server.load("fonts/FiraSans-Bold.ttf"),
                    font_size: 60.0,
                    ..default()
                },
            ),
            TextSection::from_style(TextStyle {
                font: asset_server.load("fonts/FiraSans-Bold.ttf"),
                font_size: 60.0,
                ..default()
            }),
        ])
        .with_style(Style {
            align_self: AlignSelf::FlexEnd,
            ..default()
        }),
        ContributorDisplay,
    ));
}
examples/math/render_primitives.rs (line 375)
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
fn setup_text(
    mut commands: Commands,
    asset_server: Res<AssetServer>,
    cameras: Query<(Entity, &Camera)>,
) {
    let active_camera = cameras
        .iter()
        .find_map(|(entity, camera)| camera.is_active.then_some(entity))
        .expect("run condition ensures existence");
    let text = format!("{text}", text = PrimitiveSelected::default());
    let font_size = 24.0;
    let font: Handle<Font> = asset_server.load("fonts/FiraMono-Medium.ttf");
    let style = TextStyle {
        font,
        font_size,
        color: Color::WHITE,
    };
    let instructions = "Press 'C' to switch between 2D and 3D mode\n\
        Press 'Up' or 'Down' to switch to the next/previous primitive";
    let text = [
        TextSection::new("Primitive: ", style.clone()),
        TextSection::new(text, style.clone()),
        TextSection::new("\n\n", style.clone()),
        TextSection::new(instructions, style.clone()),
        TextSection::new("\n\n", style.clone()),
        TextSection::new(
            "(If nothing is displayed, there's no rendering support yet)",
            style.clone(),
        ),
    ];

    commands
        .spawn((
            HeaderNode,
            NodeBundle {
                style: Style {
                    justify_self: JustifySelf::Center,
                    top: Val::Px(5.0),
                    ..Default::default()
                },
                ..Default::default()
            },
            TargetCamera(active_camera),
        ))
        .with_children(|parent| {
            parent.spawn((
                HeaderText,
                TextBundle::from_sections(text).with_text_justify(JustifyText::Center),
            ));
        });
}
examples/ui/ui_texture_atlas.rs (lines 62-72)
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
fn setup(
    mut commands: Commands,
    asset_server: Res<AssetServer>,
    mut texture_atlases: ResMut<Assets<TextureAtlasLayout>>,
) {
    // Camera
    commands.spawn(Camera2dBundle::default());

    let text_style = TextStyle {
        font_size: 20.,
        ..default()
    };

    let texture_handle = asset_server.load("textures/rpg/chars/gabe/gabe-idle-run.png");
    let texture_atlas = TextureAtlasLayout::from_grid(Vec2::new(24.0, 24.0), 7, 1, None, None);
    let texture_atlas_handle = texture_atlases.add(texture_atlas);

    // root node
    commands
        .spawn(NodeBundle {
            style: Style {
                width: Val::Percent(100.0),
                height: Val::Percent(100.0),
                flex_direction: FlexDirection::Column,
                justify_content: JustifyContent::Center,
                align_items: AlignItems::Center,
                row_gap: Val::Px(text_style.font_size * 2.),
                ..default()
            },
            ..default()
        })
        .with_children(|parent| {
            parent.spawn(AtlasImageBundle {
                style: Style {
                    width: Val::Px(256.),
                    height: Val::Px(256.),
                    ..default()
                },
                texture_atlas: texture_atlas_handle.into(),
                image: UiImage::new(texture_handle),
                ..default()
            });
            parent.spawn(TextBundle::from_sections([
                TextSection::new("press ".to_string(), text_style.clone()),
                TextSection::new(
                    "space".to_string(),
                    TextStyle {
                        color: Color::YELLOW,
                        ..text_style.clone()
                    },
                ),
                TextSection::new(" to advance frames".to_string(), text_style),
            ]));
        });
}
examples/window/low_power.rs (lines 170-196)
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
    pub fn setup(
        mut commands: Commands,
        mut meshes: ResMut<Assets<Mesh>>,
        mut materials: ResMut<Assets<StandardMaterial>>,
        mut event: EventWriter<RequestRedraw>,
    ) {
        commands.spawn((
            PbrBundle {
                mesh: meshes.add(Cuboid::new(0.5, 0.5, 0.5)),
                material: materials.add(Color::rgb(0.8, 0.7, 0.6)),
                ..default()
            },
            Rotator,
        ));

        commands.spawn(DirectionalLightBundle {
            transform: Transform::from_xyz(1.0, 1.0, 1.0).looking_at(Vec3::ZERO, Vec3::Y),
            ..default()
        });
        commands.spawn(Camera3dBundle {
            transform: Transform::from_xyz(-2.0, 2.0, 2.0).looking_at(Vec3::ZERO, Vec3::Y),
            ..default()
        });
        event.send(RequestRedraw);
        commands.spawn((
            TextBundle::from_sections([
                TextSection::new(
                    "Press spacebar to cycle modes\n",
                    TextStyle {
                        font_size: 50.0,
                        ..default()
                    },
                ),
                TextSection::from_style(TextStyle {
                    font_size: 50.0,
                    color: Color::GREEN,
                    ..default()
                }),
                TextSection::new(
                    "\nFrame: ",
                    TextStyle {
                        font_size: 50.0,
                        color: Color::YELLOW,
                        ..default()
                    },
                ),
                TextSection::from_style(TextStyle {
                    font_size: 50.0,
                    color: Color::YELLOW,
                    ..default()
                }),
            ])
            .with_style(Style {
                align_self: AlignSelf::FlexStart,
                position_type: PositionType::Absolute,
                top: Val::Px(5.0),
                left: Val::Px(5.0),
                ..default()
            }),
            ModeText,
        ));
    }
examples/input/text_input.rs (lines 32-81)
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
fn setup_scene(mut commands: Commands, asset_server: Res<AssetServer>) {
    commands.spawn(Camera2dBundle::default());

    let font = asset_server.load("fonts/FiraMono-Medium.ttf");

    commands.spawn(
        TextBundle::from_sections([
            TextSection {
                value: "IME Enabled: ".to_string(),
                style: TextStyle {
                    font: font.clone_weak(),
                    font_size: 20.0,
                    ..default()
                },
            },
            TextSection {
                value: "false\n".to_string(),
                style: TextStyle {
                    font: font.clone_weak(),
                    font_size: 30.0,
                    ..default()
                },
            },
            TextSection {
                value: "IME Active: ".to_string(),
                style: TextStyle {
                    font: font.clone_weak(),
                    font_size: 20.0,
                    ..default()
                },
            },
            TextSection {
                value: "false\n".to_string(),
                style: TextStyle {
                    font: font.clone_weak(),
                    font_size: 30.0,
                    ..default()
                },
            },
            TextSection {
                value: "click to toggle IME, press return to start a new line\n\n".to_string(),
                style: TextStyle {
                    font: font.clone_weak(),
                    font_size: 18.0,
                    ..default()
                },
            },
            TextSection {
                value: "".to_string(),
                style: TextStyle {
                    font,
                    font_size: 25.0,
                    ..default()
                },
            },
        ])
        .with_style(Style {
            position_type: PositionType::Absolute,
            top: Val::Px(10.0),
            left: Val::Px(10.0),
            ..default()
        }),
    );

    commands.spawn(Text2dBundle {
        text: Text::from_section(
            "".to_string(),
            TextStyle {
                font: asset_server.load("fonts/FiraMono-Medium.ttf"),
                font_size: 100.0,
                ..default()
            },
        ),
        ..default()
    });
}
source

pub const fn with_text_justify(self, justify: JustifyText) -> TextBundle

Returns this TextBundle with a new JustifyText on Text.

Examples found in repository?
examples/ui/display_and_visibility.rs (line 428)
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
fn spawn_button<T>(parent: &mut ChildBuilder, text_style: TextStyle, target: Entity)
where
    T: Default + std::fmt::Debug + Send + Sync + 'static,
    Target<T>: TargetUpdate,
{
    parent
        .spawn((
            ButtonBundle {
                style: Style {
                    align_self: AlignSelf::FlexStart,
                    padding: UiRect::axes(Val::Px(5.), Val::Px(1.)),
                    ..Default::default()
                },
                background_color: BackgroundColor(Color::BLACK.with_a(0.5)),
                ..Default::default()
            },
            Target::<T>::new(target),
        ))
        .with_children(|builder| {
            builder.spawn(
                TextBundle::from_section(
                    format!("{}::{:?}", Target::<T>::NAME, T::default()),
                    text_style,
                )
                .with_text_justify(JustifyText::Center),
            );
        });
}
More examples
Hide additional examples
examples/3d/tonemapping.rs (line 273)
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
fn setup_image_viewer_scene(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    camera_transform: Res<CameraTransform>,
) {
    let mut transform = camera_transform.0;
    transform.translation += *transform.forward();

    // exr/hdr viewer (exr requires enabling bevy feature)
    commands.spawn((
        PbrBundle {
            mesh: meshes.add(Rectangle::default()),
            material: materials.add(StandardMaterial {
                base_color_texture: None,
                unlit: true,
                ..default()
            }),
            transform,
            visibility: Visibility::Hidden,
            ..default()
        },
        SceneNumber(3),
        HDRViewer,
    ));

    commands
        .spawn((
            TextBundle::from_section(
                "Drag and drop an HDR or EXR file",
                TextStyle {
                    font_size: 36.0,
                    color: Color::BLACK,
                    ..default()
                },
            )
            .with_text_justify(JustifyText::Center)
            .with_style(Style {
                align_self: AlignSelf::Center,
                margin: UiRect::all(Val::Auto),
                ..default()
            }),
            SceneNumber(3),
        ))
        .insert(Visibility::Hidden);
}
examples/math/render_primitives.rs (line 375)
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
fn setup_text(
    mut commands: Commands,
    asset_server: Res<AssetServer>,
    cameras: Query<(Entity, &Camera)>,
) {
    let active_camera = cameras
        .iter()
        .find_map(|(entity, camera)| camera.is_active.then_some(entity))
        .expect("run condition ensures existence");
    let text = format!("{text}", text = PrimitiveSelected::default());
    let font_size = 24.0;
    let font: Handle<Font> = asset_server.load("fonts/FiraMono-Medium.ttf");
    let style = TextStyle {
        font,
        font_size,
        color: Color::WHITE,
    };
    let instructions = "Press 'C' to switch between 2D and 3D mode\n\
        Press 'Up' or 'Down' to switch to the next/previous primitive";
    let text = [
        TextSection::new("Primitive: ", style.clone()),
        TextSection::new(text, style.clone()),
        TextSection::new("\n\n", style.clone()),
        TextSection::new(instructions, style.clone()),
        TextSection::new("\n\n", style.clone()),
        TextSection::new(
            "(If nothing is displayed, there's no rendering support yet)",
            style.clone(),
        ),
    ];

    commands
        .spawn((
            HeaderNode,
            NodeBundle {
                style: Style {
                    justify_self: JustifySelf::Center,
                    top: Val::Px(5.0),
                    ..Default::default()
                },
                ..Default::default()
            },
            TargetCamera(active_camera),
        ))
        .with_children(|parent| {
            parent.spawn((
                HeaderText,
                TextBundle::from_sections(text).with_text_justify(JustifyText::Center),
            ));
        });
}
examples/time/virtual_time.rs (line 121)
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
fn setup(mut commands: Commands, asset_server: Res<AssetServer>, mut time: ResMut<Time<Virtual>>) {
    // start with double `Virtual` time resulting in one of the sprites moving at twice the speed
    // of the other sprite which moves based on `Real` (unscaled) time
    time.set_relative_speed(2.);

    commands.spawn(Camera2dBundle::default());

    let virtual_color = Color::GOLD;
    let sprite_scale = Vec2::splat(0.5).extend(1.);
    let texture_handle = asset_server.load("branding/icon.png");

    // the sprite moving based on real time
    commands.spawn((
        SpriteBundle {
            texture: texture_handle.clone(),
            transform: Transform::from_scale(sprite_scale),
            ..default()
        },
        RealTime,
    ));

    // the sprite moving based on virtual time
    commands.spawn((
        SpriteBundle {
            texture: texture_handle,
            sprite: Sprite {
                color: virtual_color,
                ..default()
            },
            transform: Transform {
                scale: sprite_scale,
                translation: Vec3::new(0., -160., 0.),
                ..default()
            },
            ..default()
        },
        VirtualTime,
    ));

    // info UI
    let font_size = 40.;

    commands
        .spawn(NodeBundle {
            style: Style {
                display: Display::Flex,
                justify_content: JustifyContent::SpaceBetween,
                width: Val::Percent(100.),
                position_type: PositionType::Absolute,
                top: Val::Px(0.),
                padding: UiRect::all(Val::Px(20.0)),
                ..default()
            },
            ..default()
        })
        .with_children(|builder| {
            // real time info
            builder.spawn((
                TextBundle::from_section(
                    "",
                    TextStyle {
                        font_size,
                        ..default()
                    },
                ),
                RealTime,
            ));

            // keybindings
            builder.spawn(
                TextBundle::from_section(
                    "CONTROLS\nUn/Pause: Space\nSpeed+: Up\nSpeed-: Down",
                    TextStyle {
                        font_size,
                        color: Color::rgb(0.85, 0.85, 0.85),
                        ..default()
                    },
                )
                .with_text_justify(JustifyText::Center),
            );

            // virtual time info
            builder.spawn((
                TextBundle::from_section(
                    "",
                    TextStyle {
                        font_size,
                        color: virtual_color,
                        ..default()
                    },
                )
                .with_text_justify(JustifyText::Right),
                VirtualTime,
            ));
        });
}
examples/ui/text.rs (line 43)
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
    // UI camera
    commands.spawn(Camera2dBundle::default());
    // Text with one section
    commands.spawn((
        // Create a TextBundle that has a Text with a single section.
        TextBundle::from_section(
            // Accepts a `String` or any type that converts into a `String`, such as `&str`
            "hello\nbevy!",
            TextStyle {
                // This font is loaded and will be used instead of the default font.
                font: asset_server.load("fonts/FiraSans-Bold.ttf"),
                font_size: 100.0,
                ..default()
            },
        ) // Set the justification of the Text
        .with_text_justify(JustifyText::Center)
        // Set the style of the TextBundle itself.
        .with_style(Style {
            position_type: PositionType::Absolute,
            bottom: Val::Px(5.0),
            right: Val::Px(5.0),
            ..default()
        }),
        ColorText,
    ));

    // Text with multiple sections
    commands.spawn((
        // Create a TextBundle that has a Text with a list of sections.
        TextBundle::from_sections([
            TextSection::new(
                "FPS: ",
                TextStyle {
                    // This font is loaded and will be used instead of the default font.
                    font: asset_server.load("fonts/FiraSans-Bold.ttf"),
                    font_size: 60.0,
                    ..default()
                },
            ),
            TextSection::from_style(if cfg!(feature = "default_font") {
                TextStyle {
                    font_size: 60.0,
                    color: Color::GOLD,
                    // If no font is specified, the default font (a minimal subset of FiraMono) will be used.
                    ..default()
                }
            } else {
                // "default_font" feature is unavailable, load a font to use instead.
                TextStyle {
                    font: asset_server.load("fonts/FiraMono-Medium.ttf"),
                    font_size: 60.0,
                    color: Color::GOLD,
                }
            }),
        ]),
        FpsText,
    ));

    #[cfg(feature = "default_font")]
    commands.spawn(
        // Here we are able to call the `From` method instead of creating a new `TextSection`.
        // This will use the default font (a minimal subset of FiraMono) and apply the default styling.
        TextBundle::from("From an &str into a TextBundle with the default font!").with_style(
            Style {
                position_type: PositionType::Absolute,
                bottom: Val::Px(5.0),
                left: Val::Px(15.0),
                ..default()
            },
        ),
    );

    #[cfg(not(feature = "default_font"))]
    commands.spawn(
        TextBundle::from_section(
            "Default font disabled",
            TextStyle {
                font: asset_server.load("fonts/FiraMono-Medium.ttf"),
                ..default()
            },
        )
        .with_style(Style {
            position_type: PositionType::Absolute,
            bottom: Val::Px(5.0),
            left: Val::Px(15.0),
            ..default()
        }),
    );
}
examples/ui/text_debug.rs (line 73)
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
fn infotext_system(mut commands: Commands, asset_server: Res<AssetServer>) {
    let font = asset_server.load("fonts/FiraSans-Bold.ttf");
    commands.spawn(Camera2dBundle::default());
    let root_uinode = commands
        .spawn(NodeBundle {
            style: Style {
                width: Val::Percent(100.),
                height: Val::Percent(100.),
                justify_content: JustifyContent::SpaceBetween,

                ..default()
            },
            ..default()
        })
        .id();

    let left_column = commands.spawn(NodeBundle {
        style: Style {
            flex_direction: FlexDirection::Column,
            justify_content: JustifyContent::SpaceBetween,
            align_items: AlignItems::Start,
            flex_grow: 1.,
            margin: UiRect::axes(Val::Px(15.), Val::Px(5.)),
            ..default()
        },
        ..default()
    }).with_children(|builder| {
        builder.spawn(
            TextBundle::from_section(
                "This is\ntext with\nline breaks\nin the top left.",
                TextStyle {
                    font: font.clone(),
                    font_size: 30.0,
                    ..default()
                },
            )
        );
        builder.spawn(TextBundle::from_section(
                "This text is right-justified. The `JustifyText` component controls the horizontal alignment of the lines of multi-line text relative to each other, and does not affect the text node's position in the UI layout.",                TextStyle {
                    font: font.clone(),
                    font_size: 30.0,
                    color: Color::YELLOW,
                },
            )
            .with_text_justify(JustifyText::Right)
            .with_style(Style {
                max_width: Val::Px(300.),
                ..default()
            })
        );
        builder.spawn(
            TextBundle::from_section(
                "This\ntext has\nline breaks and also a set width in the bottom left.",
                TextStyle {
                    font: font.clone(),
                    font_size: 30.0,
                    color: Color::WHITE,
                },
            )
            .with_style(Style {
                max_width: Val::Px(300.),
                ..default()
            })
        );
    }).id();

    let right_column = commands.spawn(NodeBundle {
        style: Style {
            flex_direction: FlexDirection::Column,
            justify_content: JustifyContent::SpaceBetween,
            align_items: AlignItems::End,
            flex_grow: 1.,
            margin: UiRect::axes(Val::Px(15.), Val::Px(5.)),
            ..default()
        },
        ..default()
    }).with_children(|builder| {

        builder.spawn(TextBundle::from_section(
                "This text is very long, has a limited width, is center-justified, is positioned in the top right and is also colored pink.",
                TextStyle {
                    font: font.clone(),
                    font_size: 40.0,
                    color: Color::rgb(0.8, 0.2, 0.7),
                },
            )
            .with_text_justify(JustifyText::Center)
            .with_style(Style {
                max_width: Val::Px(400.),
                ..default()
            })
        );

        builder.spawn(
            TextBundle::from_section(
                "This text is left-justified and is vertically positioned to distribute the empty space equally above and below it.",
                TextStyle {
                    font: font.clone(),
                    font_size: 35.0,
                    color: Color::YELLOW,
                },
            )
            .with_text_justify(JustifyText::Left)
            .with_style(Style {
                max_width: Val::Px(300.),
                ..default()
            }),
        );

        builder.spawn((
            TextBundle::from_sections([
                TextSection::new(
                    "This text changes in the bottom right",
                    TextStyle {
                        font: font.clone(),
                        font_size: 25.0,
                        color: Color::WHITE,
                    },
                ),
                TextSection::new(
                    "\nThis text changes in the bottom right - ",
                    TextStyle {
                        font: font.clone(),
                        font_size: 25.0,
                        color: Color::RED,
                    },
                ),
                TextSection::from_style(TextStyle {
                    font: font.clone(),
                    font_size: 25.0,
                    color: Color::ORANGE_RED,
                }),
                TextSection::new(
                    " fps, ",
                    TextStyle {
                        font: font.clone(),
                        font_size: 25.0,
                        color: Color::YELLOW,
                    },
                ),
                TextSection::from_style(TextStyle {
                    font: font.clone(),
                    font_size: 25.0,
                    color: Color::GREEN,
                }),
                TextSection::new(
                    " ms/frame",
                    TextStyle {
                        font: font.clone(),
                        font_size: 25.0,
                        color: Color::BLUE,
                    },
                ),
            ]),
            TextChanges,
        ));
    })
    .id();

    commands
        .entity(root_uinode)
        .push_children(&[left_column, right_column]);
}
source

pub fn with_style(self, style: Style) -> TextBundle

Returns this TextBundle with a new Style.

Examples found in repository?
examples/3d/fog.rs (lines 134-139)
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
fn setup_instructions(mut commands: Commands) {
    commands.spawn(
        TextBundle::from_section(
            "",
            TextStyle {
                font_size: 20.0,
                ..default()
            },
        )
        .with_style(Style {
            position_type: PositionType::Absolute,
            top: Val::Px(12.0),
            left: Val::Px(12.0),
            ..default()
        }),
    );
}
More examples
Hide additional examples
examples/3d/irradiance_volumes.rs (lines 306-311)
300
301
302
303
304
305
306
307
308
309
310
311
312
313
fn spawn_text(commands: &mut Commands, app_status: &AppStatus, asset_server: &AssetServer) {
    commands.spawn(
        TextBundle {
            text: app_status.create_text(asset_server),
            ..TextBundle::default()
        }
        .with_style(Style {
            position_type: PositionType::Absolute,
            bottom: Val::Px(10.0),
            left: Val::Px(10.0),
            ..default()
        }),
    );
}
examples/scene/scene.rs (lines 159-162)
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
fn infotext_system(mut commands: Commands) {
    commands.spawn(Camera2dBundle::default());
    commands.spawn(
        TextBundle::from_section(
            "Nothing to see in this window! Check the console output!",
            TextStyle {
                font_size: 50.0,
                ..default()
            },
        )
        .with_style(Style {
            align_self: AlignSelf::FlexEnd,
            ..default()
        }),
    );
}
examples/3d/reflection_probes.rs (lines 166-171)
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
fn spawn_text(commands: &mut Commands, asset_server: &AssetServer, app_status: &AppStatus) {
    // Create the text.
    commands.spawn(
        TextBundle {
            text: app_status.create_text(asset_server),
            ..TextBundle::default()
        }
        .with_style(Style {
            position_type: PositionType::Absolute,
            bottom: Val::Px(10.0),
            left: Val::Px(10.0),
            ..default()
        }),
    );
}
examples/3d/atmospheric_fog.rs (lines 105-110)
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
fn setup_instructions(mut commands: Commands) {
    commands.spawn(
        TextBundle::from_section(
            "Press Spacebar to Toggle Atmospheric Fog.\nPress S to Toggle Directional Light Fog Influence.",
            TextStyle {
                font_size: 20.0,
                ..default()
            },
        )
        .with_style(Style {
            position_type: PositionType::Absolute,
            bottom: Val::Px(12.0),
            left: Val::Px(12.0),
            ..default()
        }),
    );
}
examples/games/stepping.rs (lines 195-200)
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
fn build_help(mut commands: Commands, asset_server: Res<AssetServer>) {
    // stepping description box
    commands.spawn((TextBundle::from_sections([TextSection::new(
        "Press ` to toggle stepping mode (S: step system, Space: step frame)",
        TextStyle {
            font: asset_server.load(FONT_MEDIUM),
            font_size: 18.0,
            color: FONT_COLOR,
        },
    )])
    .with_style(Style {
        position_type: PositionType::Absolute,
        bottom: Val::Px(5.0),
        left: Val::Px(5.0),
        ..default()
    }),));
}
source

pub const fn with_background_color(self, color: Color) -> TextBundle

Returns this TextBundle with a new BackgroundColor.

source

pub const fn with_no_wrap(self) -> TextBundle

Returns this TextBundle with soft wrapping disabled. Hard wrapping, where text contains an explicit linebreak such as the escape sequence \n, will still occur.

Examples found in repository?
examples/3d/blend_modes.rs (line 237)
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    asset_server: Res<AssetServer>,
) {
    let base_color = Color::rgba(0.9, 0.2, 0.3, 1.0);
    let icosphere_mesh = meshes.add(Sphere::new(0.9).mesh().ico(7).unwrap());

    // Opaque
    let opaque = commands
        .spawn((
            PbrBundle {
                mesh: icosphere_mesh.clone(),
                material: materials.add(StandardMaterial {
                    base_color,
                    alpha_mode: AlphaMode::Opaque,
                    ..default()
                }),
                transform: Transform::from_xyz(-4.0, 0.0, 0.0),
                ..default()
            },
            ExampleControls {
                unlit: true,
                color: true,
            },
        ))
        .id();

    // Blend
    let blend = commands
        .spawn((
            PbrBundle {
                mesh: icosphere_mesh.clone(),
                material: materials.add(StandardMaterial {
                    base_color,
                    alpha_mode: AlphaMode::Blend,
                    ..default()
                }),
                transform: Transform::from_xyz(-2.0, 0.0, 0.0),
                ..default()
            },
            ExampleControls {
                unlit: true,
                color: true,
            },
        ))
        .id();

    // Premultiplied
    let premultiplied = commands
        .spawn((
            PbrBundle {
                mesh: icosphere_mesh.clone(),
                material: materials.add(StandardMaterial {
                    base_color,
                    alpha_mode: AlphaMode::Premultiplied,
                    ..default()
                }),
                transform: Transform::from_xyz(0.0, 0.0, 0.0),
                ..default()
            },
            ExampleControls {
                unlit: true,
                color: true,
            },
        ))
        .id();

    // Add
    let add = commands
        .spawn((
            PbrBundle {
                mesh: icosphere_mesh.clone(),
                material: materials.add(StandardMaterial {
                    base_color,
                    alpha_mode: AlphaMode::Add,
                    ..default()
                }),
                transform: Transform::from_xyz(2.0, 0.0, 0.0),
                ..default()
            },
            ExampleControls {
                unlit: true,
                color: true,
            },
        ))
        .id();

    // Multiply
    let multiply = commands
        .spawn((
            PbrBundle {
                mesh: icosphere_mesh,
                material: materials.add(StandardMaterial {
                    base_color,
                    alpha_mode: AlphaMode::Multiply,
                    ..default()
                }),
                transform: Transform::from_xyz(4.0, 0.0, 0.0),
                ..default()
            },
            ExampleControls {
                unlit: true,
                color: true,
            },
        ))
        .id();

    // Chessboard Plane
    let black_material = materials.add(Color::BLACK);
    let white_material = materials.add(Color::WHITE);

    let plane_mesh = meshes.add(Plane3d::default().mesh().size(2.0, 2.0));

    for x in -3..4 {
        for z in -3..4 {
            commands.spawn((
                PbrBundle {
                    mesh: plane_mesh.clone(),
                    material: if (x + z) % 2 == 0 {
                        black_material.clone()
                    } else {
                        white_material.clone()
                    },
                    transform: Transform::from_xyz(x as f32 * 2.0, -1.0, z as f32 * 2.0),
                    ..default()
                },
                ExampleControls {
                    unlit: false,
                    color: true,
                },
            ));
        }
    }

    // Light
    commands.spawn(PointLightBundle {
        transform: Transform::from_xyz(4.0, 8.0, 4.0),
        ..default()
    });

    // Camera
    commands.spawn(Camera3dBundle {
        transform: Transform::from_xyz(0.0, 2.5, 10.0).looking_at(Vec3::ZERO, Vec3::Y),
        ..default()
    });

    // Controls Text
    let text_style = TextStyle {
        font: asset_server.load("fonts/FiraMono-Medium.ttf"),
        font_size: 18.0,
        ..default()
    };

    let label_text_style = TextStyle {
        font: asset_server.load("fonts/FiraMono-Medium.ttf"),
        font_size: 25.0,
        color: Color::ORANGE,
    };

    commands.spawn(
        TextBundle::from_section(
            "Up / Down — Increase / Decrease Alpha\nLeft / Right — Rotate Camera\nH - Toggle HDR\nSpacebar — Toggle Unlit\nC — Randomize Colors",
            text_style.clone(),
        )
        .with_style(Style {
            position_type: PositionType::Absolute,
            top: Val::Px(10.0),
            left: Val::Px(10.0),
            ..default()
        }),
    );

    commands.spawn((
        TextBundle::from_section("", text_style).with_style(Style {
            position_type: PositionType::Absolute,
            top: Val::Px(10.0),
            right: Val::Px(10.0),
            ..default()
        }),
        ExampleDisplay,
    ));

    let mut label = |entity: Entity, label: &str| {
        commands
            .spawn((
                NodeBundle {
                    style: Style {
                        position_type: PositionType::Absolute,
                        ..default()
                    },
                    ..default()
                },
                ExampleLabel { entity },
            ))
            .with_children(|parent| {
                parent.spawn(
                    TextBundle::from_section(label, label_text_style.clone())
                        .with_style(Style {
                            position_type: PositionType::Absolute,
                            bottom: Val::ZERO,
                            ..default()
                        })
                        .with_no_wrap(),
                );
            });
    };

    label(opaque, "┌─ Opaque\n│\n│\n│\n│");
    label(blend, "┌─ Blend\n│\n│\n│");
    label(premultiplied, "┌─ Premultiplied\n│\n│");
    label(add, "┌─ Add\n│");
    label(multiply, "┌─ Multiply");
}

Trait Implementations§

source§

impl Debug for TextBundle

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
source§

impl Default for TextBundle

source§

fn default() -> TextBundle

Returns the “default value” for a type. Read more
source§

impl<I> From<I> for TextBundle
where I: Into<TextSection>,

source§

fn from(value: I) -> TextBundle

Converts to this type from the input type.
source§

impl Bundle for TextBundle

source§

impl DynamicBundle for TextBundle

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T, U> AsBindGroupShaderType<U> for T
where U: ShaderType, &'a T: for<'a> Into<U>,

source§

fn as_bind_group_shader_type(&self, _images: &RenderAssets<Image>) -> U

Return the T ShaderType for self. When used in AsBindGroup derives, it is safe to assume that all images in self exist.
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> Downcast<T> for T

source§

fn downcast(&self) -> &T

source§

impl<T> Downcast for T
where T: Any,

source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<S> FromSample<S> for S

source§

fn from_sample_(s: S) -> S

source§

impl<T> FromWorld for T
where T: Default,

source§

fn from_world(_world: &mut World) -> T

Creates Self using data from the given World.
source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

source§

fn to_sample_(self) -> U

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> Upcast<T> for T

source§

fn upcast(&self) -> Option<&T>

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

source§

impl<T> Settings for T
where T: 'static + Send + Sync,

source§

impl<T> WasmNotSend for T
where T: Send,

source§

impl<T> WasmNotSendSync for T

source§

impl<T> WasmNotSync for T
where T: Sync,