docs/bevy/examples/ui/text/generic_font_families.rs 3.3 K · 99 lines · raw · history

1 //! This example demonstrates generic font families,
2 //! which allow font faces to be selected using broadly defined
3 //! categories (such as serif or monospace) without selecting
4 //! a specific font family.
5 //!
6 //! Each generic font family is first resolved to a concrete
7 //! family name, which is then matched to a font in the internal
8 //! font database. This example loads system installed fonts to
9 //! populate the database.
10 //!
11 //! This feature is most useful for non-game applications;
12 //! most games instead choose to simply bundle their required fonts
13 //! to ensure a unified visual look.
14
15 use bevy::{
16 color::palettes::{
17 css::{WHEAT, YELLOW},
18 tailwind::ZINC_600,
19 },
20 prelude::*,
21 text::FontCx,
22 };
23
24 fn main() {
25 let mut app = App::new();
26 app.add_plugins(DefaultPlugins).add_systems(Startup, setup);
27
28 app.run();
29 }
30
31 const FONT_SIZE: FontSize = FontSize::Px(25.);
32
33 fn setup(mut commands: Commands, mut font_system: ResMut<FontCx>) {
34 // UI camera
35 commands.spawn(Camera2d);
36
37 commands
38 .spawn((Node {
39 display: Display::Grid,
40 grid_template_columns: vec![RepeatedGridTrack::fr(3, 1.)],
41 margin: UiRect::AUTO,
42 row_gap: px(25),
43 column_gap: px(15),
44 ..Default::default()
45 },))
46 .with_children(|builder| {
47 builder.spawn((
48 Node {
49 justify_self: JustifySelf::Center,
50 grid_column: GridPlacement::span(3),
51 margin: UiRect::bottom(px(15)),
52 ..default()
53 },
54 Text::new("Generic Font Families"),
55 TextFont::from_font_size(FONT_SIZE),
56 Underline,
57 ));
58
59 let outline = Outline {
60 color: ZINC_600.into(),
61 width: px(2.),
62 offset: px(4.),
63 };
64
65 for (source, description) in [
66 (FontSource::sans_serif(), "generic sans serif font"),
67 (FontSource::serif(), "generic serif font"),
68 (FontSource::fantasy(), "generic fantasy font"),
69 (FontSource::cursive(), "generic cursive font"),
70 (FontSource::monospace(), "generic monospace font"),
71 ] {
72 builder.spawn((
73 Text::new(description),
74 TextFont::from(source.clone()).with_font_size(FONT_SIZE),
75 TextColor(WHEAT.into()),
76 TextLayout::justify(Justify::Center),
77 outline,
78 ));
79
80 builder.spawn((
81 Text::new(format!("FontSource::{source:?}")),
82 TextFont::from_font_size(FONT_SIZE),
83 TextColor(YELLOW.into()),
84 TextLayout::justify(Justify::Center),
85 outline,
86 ));
87
88 // Get the family name for the `FontSource` from `FontCx`.
89 // `get_family` only returns `None` for `FontSource::Handle`.
90 let family_name = font_system.get_family(&source).unwrap();
91 builder.spawn((
92 Text::new(family_name),
93 TextFont::from_font_size(FONT_SIZE),
94 TextLayout::justify(Justify::Center),
95 outline,
96 ));
97 }
98 });
99 }