Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/examples/ui/text/system_fonts.rs
9331 views
1
//! This example displays a scrollable list of all available system fonts.
2
//! Demonstrates loading and querying system fonts via cosmic-text.
3
4
use bevy::{
5
diagnostic::FrameTimeDiagnosticsPlugin, input::mouse::MouseScrollUnit, prelude::*,
6
text::CosmicFontSystem,
7
};
8
9
fn main() {
10
let mut app = App::new();
11
app.add_plugins((DefaultPlugins, FrameTimeDiagnosticsPlugin::default()))
12
.add_systems(Startup, setup);
13
14
app.world_mut()
15
.resource_mut::<CosmicFontSystem>()
16
.db_mut()
17
.load_system_fonts();
18
19
app.run();
20
}
21
22
fn setup(mut commands: Commands, font_system: Res<CosmicFontSystem>) {
23
commands.spawn(Camera2d);
24
25
commands
26
.spawn((
27
Node {
28
flex_direction: FlexDirection::Column,
29
width: percent(100),
30
height: percent(100),
31
align_items: AlignItems::Center,
32
row_gap: px(10.),
33
..default()
34
},
35
BackgroundColor(Color::srgb(0.1, 0.1, 0.1)),
36
))
37
.with_children(|builder| {
38
builder.spawn(Text::new(format!(
39
"Total available fonts: {}",
40
font_system.db().len(),
41
)));
42
43
builder
44
.spawn(Node {
45
flex_direction: FlexDirection::Column,
46
row_gap: px(6),
47
overflow: Overflow::scroll_y(),
48
align_items: AlignItems::Stretch,
49
..default()
50
})
51
.with_children(|builder| {
52
let mut families: Vec<(String, String)> = Vec::new();
53
for face in font_system.db().faces() {
54
for (name, lang) in &face.families {
55
families.push((name.to_string(), lang.to_string()));
56
}
57
}
58
families.sort_unstable();
59
families.dedup();
60
for (family, language) in families {
61
builder.spawn((
62
Node {
63
display: Display::Grid,
64
grid_template_columns: vec![
65
GridTrack::flex(1.),
66
GridTrack::flex(1.),
67
GridTrack::flex(1.),
68
],
69
padding: px(6).all(),
70
column_gap: px(50.),
71
..default()
72
},
73
BackgroundColor(Color::srgb(0.2, 0.2, 0.25)),
74
children![
75
(
76
Text::new(&family),
77
TextFont {
78
font: FontSource::Family(family.as_str().into()),
79
..default()
80
},
81
TextLayout::new_with_no_wrap()
82
),
83
(Text::new(family), TextLayout::new_with_no_wrap()),
84
(
85
Text::new(language),
86
TextLayout::new_with_no_wrap(),
87
Node {
88
justify_self: JustifySelf::End,
89
..default()
90
}
91
)
92
],
93
));
94
}
95
})
96
.observe(
97
|on_scroll: On<Pointer<Scroll>>,
98
mut query: Query<(&mut ScrollPosition, &ComputedNode)>| {
99
if let Ok((mut scroll_position, node)) = query.get_mut(on_scroll.entity) {
100
let dy = match on_scroll.unit {
101
MouseScrollUnit::Line => on_scroll.y * 20.,
102
MouseScrollUnit::Pixel => on_scroll.y,
103
};
104
let range = (node.content_size.y - node.size.y).max(0.)
105
* node.inverse_scale_factor;
106
scroll_position.y = (scroll_position.y - dy).clamp(0., range);
107
}
108
},
109
);
110
});
111
}
112
113