Path: blob/main/examples/ui/text/generic_font_families.rs
9416 views
//! This example demonstrates generic font families,1//! which allow font faces to be selected using broadly defined2//! categories (such as serif or monospace) without selecting3//! a specific font family.4//!5//! Each generic font family is first resolved to a concrete6//! family name, which is then matched to a font in the internal7//! font database. This example loads system installed fonts to8//! populate the database.9//!10//! This feature is most useful for non-game applications;11//! most games instead choose to simply bundle their required fonts12//! to ensure a unified visual look.1314use bevy::{15color::palettes::{16css::{WHEAT, YELLOW},17tailwind::ZINC_600,18},19prelude::*,20text::FontCx,21};2223fn main() {24let mut app = App::new();25app.add_plugins(DefaultPlugins).add_systems(Startup, setup);2627app.run();28}2930const FONT_SIZE: FontSize = FontSize::Px(25.);3132fn setup(mut commands: Commands, mut font_system: ResMut<FontCx>) {33// UI camera34commands.spawn(Camera2d);3536commands37.spawn((Node {38display: Display::Grid,39grid_template_columns: vec![RepeatedGridTrack::fr(3, 1.)],40margin: UiRect::AUTO,41row_gap: px(25),42column_gap: px(15),43..Default::default()44},))45.with_children(|builder| {46builder.spawn((47Node {48justify_self: JustifySelf::Center,49grid_column: GridPlacement::span(3),50margin: UiRect::bottom(px(15)),51..default()52},53Text::new("Generic Font Families"),54TextFont::from_font_size(FONT_SIZE),55Underline,56));5758let outline = Outline {59color: ZINC_600.into(),60width: px(2.),61offset: px(4.),62};6364for (source, description) in [65(FontSource::SansSerif, "generic sans serif font"),66(FontSource::Serif, "generic serif font"),67(FontSource::Fantasy, "generic fantasy font"),68(FontSource::Cursive, "generic cursive font"),69(FontSource::Monospace, "generic monospace font"),70] {71builder.spawn((72Text::new(description),73TextFont::from(source.clone()).with_font_size(FONT_SIZE),74TextColor(WHEAT.into()),75TextLayout::new_with_justify(Justify::Center),76outline,77));7879builder.spawn((80Text::new(format!("FontSource::{source:?}")),81TextFont::from_font_size(FONT_SIZE),82TextColor(YELLOW.into()),83TextLayout::new_with_justify(Justify::Center),84outline,85));8687// Get the family name for the `FontSource` from `FontCx`.88// `get_family` only returns `None` for `FontSource::Handle`.89let family_name = font_system.get_family(&source).unwrap();90builder.spawn((91Text::new(family_name),92TextFont::from_font_size(FONT_SIZE),93TextLayout::new_with_justify(Justify::Center),94outline,95));96}97});98}99100101