Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_feathers/src/font_styles.rs
6595 views
1
//! A framework for inheritable font styles.
2
use bevy_app::Propagate;
3
use bevy_asset::{AssetServer, Handle};
4
use bevy_ecs::{
5
component::Component,
6
lifecycle::Insert,
7
observer::On,
8
reflect::ReflectComponent,
9
system::{Commands, Query, Res},
10
};
11
use bevy_reflect::{prelude::ReflectDefault, Reflect};
12
use bevy_text::{Font, TextFont};
13
14
use crate::handle_or_path::HandleOrPath;
15
16
/// A component which, when inserted on an entity, will load the given font and propagate it
17
/// downward to any child text entity that has the [`ThemedText`](crate::theme::ThemedText) marker.
18
#[derive(Component, Default, Clone, Debug, Reflect)]
19
#[reflect(Component, Default)]
20
pub struct InheritableFont {
21
/// The font handle or path.
22
pub font: HandleOrPath<Font>,
23
/// The desired font size.
24
pub font_size: f32,
25
}
26
27
impl InheritableFont {
28
/// Create a new `InheritableFont` from a handle.
29
pub fn from_handle(handle: Handle<Font>) -> Self {
30
Self {
31
font: HandleOrPath::Handle(handle),
32
font_size: 16.0,
33
}
34
}
35
36
/// Create a new `InheritableFont` from a path.
37
pub fn from_path(path: &str) -> Self {
38
Self {
39
font: HandleOrPath::Path(path.to_string()),
40
font_size: 16.0,
41
}
42
}
43
}
44
45
/// An observer which looks for changes to the `InheritableFont` component on an entity, and
46
/// propagates downward the font to all participating text entities.
47
pub(crate) fn on_changed_font(
48
ev: On<Insert, InheritableFont>,
49
font_style: Query<&InheritableFont>,
50
assets: Res<AssetServer>,
51
mut commands: Commands,
52
) {
53
if let Ok(style) = font_style.get(ev.entity())
54
&& let Some(font) = match style.font {
55
HandleOrPath::Handle(ref h) => Some(h.clone()),
56
HandleOrPath::Path(ref p) => Some(assets.load::<Font>(p)),
57
}
58
{
59
commands.entity(ev.entity()).insert(Propagate(TextFont {
60
font,
61
font_size: style.font_size,
62
..Default::default()
63
}));
64
}
65
}
66
67