We can change the font, size and color of texts.
Assume we have a font file FiraSans-Bold.ttf in the assets
directory.
We can set the font, font_size and color of TextStyle when we create a Text.
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2dBundle::default());
commands.spawn(Text2dBundle {
text: Text::from_section(
"Hello",
TextStyle {
font: asset_server.load("FiraSans-Bold.ttf"),
font_size: 100.,
color: Color::hsl(210., 1., 0.8),
},
),
..default()
});
}
We use the resource AssetServer to load the font, just like how we load an image.
The full code is as follows:
use bevy::{
app::{App, Startup},
asset::AssetServer,
core_pipeline::core_2d::Camera2dBundle,
ecs::system::{Commands, Res},
render::color::Color,
text::{Text, Text2dBundle, TextStyle},
utils::default,
DefaultPlugins,
};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2dBundle::default());
commands.spawn(Text2dBundle {
text: Text::from_section(
"Hello",
TextStyle {
font: asset_server.load("FiraSans-Bold.ttf"),
font_size: 100.,
color: Color::hsl(210., 1., 0.8),
},
),
..default()
});
}
Result:
A text can have different styles for different substrings. To achieve this, instead of using Text::from_section, we use Text::from_sections. The function Text::from_sections accepts an array of TextSection, where each TextSection describes a string and its style.
use bevy::{
app::{App, Startup},
asset::AssetServer,
core_pipeline::core_2d::Camera2dBundle,
ecs::system::{Commands, Res},
render::color::Color,
text::{Text, Text2dBundle, TextSection, TextStyle},
utils::default,
DefaultPlugins,
};
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_systems(Startup, setup)
.run();
}
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2dBundle::default());
commands.spawn(Text2dBundle {
text: Text::from_sections([
TextSection::new(
"Hello ",
TextStyle {
font_size: 100.,
color: Color::hsl(210., 1., 0.7),
..default()
},
),
TextSection::new(
"World",
TextStyle {
font: asset_server.load("FiraSans-Bold.ttf"),
font_size: 120.,
color: Color::hsl(30., 1., 0.6),
},
),
]),
..default()
});
}
Result:
➡️ Next: Text Positions
📘 Back: Table of contents