前言
上一篇文章中介绍了如何使用egui创建一个应用程序,但还存在问题,app的字体仅支持英文,还不支持中文。而且当时代码都在main方法中没有进行拆分。本文主要解决这两个问题
代码
以下是完整代码。代码中自定义了软件的字体,
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] // hide console window on Windows in release
#![allow(rustdoc::missing_crate_level_docs)] // it's an example
use eframe::egui;
fn main() -> eframe::Result {
# 设置基础配置项
let options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default().with_inner_size([320.0, 240.0]),
..Default::default()
};
# 注意这行代码,在第一篇教程中这个方法是run_simple_native
eframe::run_native(
"pic匹克", # 标题设置中文一会儿启动看是否能正常显示
options,
Box::new(|cc| Ok(Box::new(PicPicApp::new(cc)))),
)
}
struct PicPicApp {
name: String,
age: u32,
}
impl PicPicApp {
fn new(cc: &eframe::CreationContext<'_>) -> Self {
# 设置自定义字体,该方法定义在最下方了
setup_custom_fonts(&cc.egui_ctx);
Self {
name: "Aspirin".to_owned(),
age: 18,
}
}
}
impl eframe::App for PicPicApp {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
egui::CentralPanel::default().show(ctx, |ui| {
ui.heading("pic匹克");
ui.horizontal(|ui| {
let name_label = ui.label("Your name: ");
ui.text_edit_singleline(&mut self.name)
.labelled_by(name_label.id);
});
ui.add(egui::Slider::new(&mut self.age, 0..=120).text("age"));
if ui.button("Increment").clicked() {
self.age += 1;
}
ui.label(format!("Hello '{}', age {}", self.name, self.age));
});
}
}
# 自定义字体的方法
fn setup_custom_fonts(ctx: &egui::Context) {
// Start with the default fonts (we will be adding to them rather than replacing them).
let mut fonts = egui::FontDefinitions::default();
// Install my own font (maybe supporting non-latin characters).
// .ttf and .otf files supported.
fonts.font_data.insert(
"my_font".to_owned(),
egui::FontData::from_static(include_bytes!(
"../fonts/FangZhengFangSongJianTi.ttf"
)),
);
// Put my font first (highest priority) for proportional text:
fonts
.families
.entry(egui::FontFamily::Proportional)
.or_default()
.insert(0, "my_font".to_owned());
// Put my font as last fallback for monospace:
fonts
.families
.entry(egui::FontFamily::Monospace)
.or_default()
.push("my_font".to_owned());
// Tell egui to use these fonts:
ctx.set_fonts(fonts);
}