Skip to content

Instantly share code, notes, and snippets.

@tinaun
Last active May 30, 2023 02:45
Show Gist options
  • Save tinaun/c135d891ccdc261f2a6ea6ada406e229 to your computer and use it in GitHub Desktop.
Save tinaun/c135d891ccdc261f2a6ea6ada406e229 to your computer and use it in GitHub Desktop.
using fontdb to load system fonts
use fontdb::{Database, Family, Query, Source};
use eframe::egui;
use std::{fs, io};
fn cjk_font_query() -> Query<'static> {
Query {
families: &[
Family::Name("MS UI Gothic"),
Family::Name("Arial Unicode MS"),
Family::Name("Noto Sans"),
Family::SansSerif,
],
..Query::default()
}
}
fn to_font_data(src: Source) -> io::Result<egui::FontData> {
match src {
Source::File(path) => {
let data = fs::read(path)?;
Ok(egui::FontData::from_owned(data))
}
Source::Binary(bin) | Source::SharedFile(_, bin) => {
let data = bin.as_ref().as_ref().to_vec();
Ok(egui::FontData::from_owned(data))
}
}
}
fn main() {
let mut font_database = Database::new();
font_database.load_system_fonts();
let font_defs = font_database.query(&cjk_font_query()).and_then(|id| {
let name = font_database.face(id).map(|i| i.post_script_name.clone())?;
let (src, n) = font_database.face_source(id)?;
Some((name, src, n))
});
let definitions = if let Some((name, src, n)) = font_defs {
let mut fontdata = to_font_data(src).unwrap();
fontdata.index = n;
let mut fd = egui::FontDefinitions::default();
fd.font_data.insert(name.clone(), fontdata);
fd.families
.get_mut(&egui::FontFamily::Proportional)
.unwrap()
.push(name.clone());
Some(fd)
} else {
None
};
let native_options = eframe::NativeOptions::default();
let _ = eframe::run_native(
"font fallback",
native_options,
Box::new(|cc| Box::new(CJKDemo::new(cc, definitions))),
);
}
#[derive(Default)]
struct CJKDemo {}
impl CJKDemo {
fn new(cc: &eframe::CreationContext<'_>, definitions: Option<egui::FontDefinitions>) -> Self {
if let Some(defs) = definitions {
cc.egui_ctx.set_fonts(defs);
}
Self::default()
}
}
impl eframe::App for CJKDemo {
fn update(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) {
egui::CentralPanel::default().show(ctx, |ui| {
ui.heading("Hello World 漢字?");
ui.heading("مقالة اليوم المختارة");
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment