第十章 字体与样式¶
egui 的外观完全可以自定义。本章讲怎么改字体、改颜色、改间距。
0.37 里
Context::style()/set_style()已改名global_style()/set_global_style(),另有global_style_mut(|s| ..)。老代码里的ctx.style()编译不过时,改这三个名字就行。
10.1 默认字体¶
egui 自带的字体在 epaint_default_fonts crate 的 fonts/ 目录里(FontDefinitions::default() 把它们装好):
| 字体 | 用途 | 何时存在 |
|---|---|---|
Ubuntu-Light.ttf |
默认 proportional 字体 | 开了 default_fonts |
Hack-Regular.ttf |
默认 monospace 字体 | 开了 default_fonts |
egui-icons.ttf |
egui::special_emojis 里的那几个图标 |
开了 default_fonts |
NotoEmoji-Regular.ttf |
单色 emoji | 额外开了 egui 的 monochrome_emoji_fonts |
emoji-icon-font.ttf |
另一套 emoji 图标 | 额外开了 egui 的 monochrome_emoji_fonts |
eframe的默认 feature 里有default_fonts,但没有monochrome_emoji_fonts:默认情况下没有内嵌 emoji 字体。
默认字体不支持中文,缺字会画成方框(tofu)。要显示中文有两条路:
- 在
eframe的桌面端什么都不做:eframe默认会去系统里找字体兜底(见 10.2 后半)。 - 自己把字体打包进程序(10.2、10.3),样式统一、各机器显示一致。
10.2 加中文字体¶
最简单的办法:用 ctx.add_font 在已有字体上追加一个。
use egui::{FontInsert, FontPriority, InsertFontFamily};
fn add_chinese_font(ctx: &egui::Context) {
ctx.add_font(FontInsert::new(
"my_font",
egui::FontData::from_static(include_bytes!("../assets/SourceHanSansCN-Regular.otf")),
vec![
InsertFontFamily {
family: egui::FontFamily::Proportional,
priority: FontPriority::Highest, // 排在现有字体之前
},
InsertFontFamily {
family: egui::FontFamily::Monospace,
priority: FontPriority::Lowest, // 排在现有字体之后,等宽兜底
},
],
));
}
在 App 创建时调一次:
impl MyApp {
fn new(cc: &eframe::CreationContext<'_>) -> Self {
add_chinese_font(&cc.egui_ctx);
Self::default()
}
}
| 类型 | 说明 |
|---|---|
FontInsert::new(name, data, families) |
一个字体 + 它要加入哪些族 |
FontData::from_static(bytes) / from_owned(vec) |
支持 .ttf 和 .otf |
FontPriority::Highest |
排到现有字体前面:只要这个字体有该字形,就用它 |
FontPriority::Lowest |
排到现有字体后面:只有前面的字体都没有该字形才用它 |
Highest的字体里如果也有拉丁字母,英文也会改用它来画。想保留 egui 原来的英文字形、只补中文,两个族都用Lowest。
add_font按名字判重:同名字体已存在就直接忽略,所以重复调用无害,但想“换掉同名字体”要用set_fonts(见 10.3)。字体在下一个 pass 开始时生效。
更省事的办法:用系统字体兜底(0.37 新增)¶
上面那套是“把字体文件打包进程序”的老办法:可靠,但字体动辄几十 MB,而且很难覆盖生僻字。
0.37 新增了 crate egui_system_font_provider:当所有已装字体都画不了某个字时,它按需去系统里找一个能画的字体(Windows 走 DirectWrite,macOS 走 CoreText,Linux 走 fontconfig,Android 读 fonts.xml;底层是 fontique),把这个字体文件内存映射进来,追加到该字体族的兜底链末尾,之后像普通字体一样排版。
用 eframe 的桌面端通常不用写任何代码:
| 项 | 说明 |
|---|---|
eframe 的 system_fonts feature |
在 eframe 默认 features 里 |
NativeOptions::system_font_fallback |
默认 true,eframe 会自动 ctx.add_font_provider(SystemFontProvider::new()) |
| 想关掉 | system_font_fallback: false(需要各机器显示完全一致、或字体已全部自带时) |
eframe 以外的集成(或 web,eframe 在 web 上用的是浏览器栅格化)才需要自己加:
fn add_system_fonts(ctx: &egui::Context) {
ctx.add_font_provider(std::sync::Arc::new(
egui_system_font_provider::SystemFontProvider::new(),
));
}
几点值得知道:
- 它只是“兜底”,不会改你的字体优先级;
FontProvider找到的字体永远排在配置好的字体之后。想统一字体风格(比如全用思源黑体)还是得用上面的FontInsert。 SystemFontProvider::new()会在后台线程枚举系统字体;第一次遇到缺字时如果还没枚举完,会阻塞到完成。- 多个汉字区域(简中/繁中/日/韩)共用一套汉字时,靠系统语言挑字体:
SystemFontProvider::new().with_locale(Some("zh-Hans"))可以指定。 - 系统 emoji 字体目前被跳过(它们是位图/彩色字形,epaint 暂时画不了)。emoji 要靠 egui 的
monochrome_emoji_fontsfeature,或自己用ctx.add_glyph_rasterizer(GlyphRasterizer::new(..))接管单个字形。 - 自己用
ctx.set_fonts完全接管字体表时,provider 仍然生效,它管的是“字体表里都找不到”的字。ctx.set_font_providers(vec![])可以一次清掉所有 provider。
10.3 完全替换字体表¶
如果你想把整个字体表换成自己的:
fn replace_fonts(ctx: &egui::Context) {
let mut fonts = egui::FontDefinitions::default();
fonts.font_data.insert(
"my_font".to_owned(),
std::sync::Arc::new(egui::FontData::from_static(include_bytes!(
"../assets/MyFont-Regular.ttf"
))),
);
// proportional 优先用 my_font
fonts
.families
.entry(egui::FontFamily::Proportional)
.or_default()
.insert(0, "my_font".to_owned());
// monospace 也加 my_font 作为兜底
fonts
.families
.entry(egui::FontFamily::Monospace)
.or_default()
.push("my_font".to_owned());
ctx.set_fonts(fonts);
}
FontDefinitions 里:
font_data: BTreeMap<String, Arc<FontData>>:所有字体数据,按名字索引。families: BTreeMap<FontFamily, Vec<String>>:每个FontFamily是一组字体名(按优先级排序)。egui 找不到字符时按顺序往下找。
把中文字体放在 Proportional 列表前几位,中文就能显示了。保留默认字体很重要——否则英文字符可能没字体可用。FontDefinitions::empty() 是真正的“一个字体都没有”。
FontFamily 除了 Proportional / Monospace,还有 Name(Arc<str>):往 families 里插一个自定义名字的族,就能在 RichText::family(..) / FontId::new(.., FontFamily::Name(..)) 里用(比如专门放一个粗体字体,见 10.10)。
注意
default_fontsfeature:egui 0.37 起它不是默认 feature 了(0.34 里还是default = ["default_fonts"])。用eframe时默认开着,但如果你直接依赖egui并写了default-features = false,FontDefinitions::default()就是空的(没有任何内嵌字体),需要手动加features = ["default_fonts"]。
10.4 字体大小¶
全局字号:
ctx.global_style_mut(|style| {
style.text_styles.insert(
egui::TextStyle::Body,
egui::FontId::new(18.0, egui::FontFamily::Proportional),
);
});
TextStyle 有几个预设:Small、Body、Monospace、Button、Heading、Name(Arc<str>)(自己起名字)。FontId::new(size, family),也有 FontId::proportional(size) / FontId::monospace(size)。
global_style_mut只改当前主题(深色或浅色)的那份Style。想两个主题都改,用ctx.all_styles_mut(|style| ..);指定某个主题用ctx.style_mut_of(egui::Theme::Dark, |style| ..)。
局部改字号用 RichText:
ui.label(egui::RichText::new("大字").size(28.0));
ui.label(egui::RichText::new("小字").size(10.0));
ui.label(egui::RichText::new("标题").text_style(egui::TextStyle::Heading));
10.5 Style(全局样式)¶
ctx.global_style() 返回 Arc<Style>。要改,用 global_style_mut(内部会 Arc::make_mut),或者 clone 一份再 set_global_style:
ctx.global_style_mut(|style| {
style.spacing.item_spacing = egui::vec2(10.0, 6.0);
style.spacing.button_padding = egui::vec2(12.0, 4.0);
style.spacing.indent = 24.0;
style.spacing.scroll.bar_width = 12.0;
style.spacing.extra_text_line_spacing = 4.0; // 文本行之间的额外垂直间距
});
// 等价的 clone 写法
let mut style: egui::Style = (*ctx.global_style()).clone();
style.spacing.item_spacing = egui::vec2(10.0, 6.0);
ctx.set_global_style(style);
滚动条宽度不再是
spacing.scroll_bar_width,而是spacing.scroll.bar_width(spacing.scroll是ScrollStyle,里面还有floating、handle_min_length、content_margin等)。
Style 包含:
spacing: Spacing:间距、控件高度、缩进等。item_spacing、button_padding、indent、interact_size(控件最小可交互尺寸,.y是按钮/滑块默认高度)。slider_width、combo_width、text_edit_width、icon_width。window_margin、menu_margin:Margin类型。extra_text_line_spacing: f32:文本行之间的额外垂直间距,用于改善文本可读性。scroll: ScrollStyle:滚动条样式。visuals: Visuals:颜色(暗色/亮色主题、控件颜色)。text_styles: BTreeMap<TextStyle, FontId>:每种文本样式的字号字体。animation_time: f32:动画时长。interaction: Interaction:interact_radius、resize_grab_radius_side/corner、tooltip_delay、show_tooltips_only_when_still、selectable_labels(Label 能否选中文字)、multi_widget_text_select等。
只改一个 Ui 内的样式:
深色和浅色是两份 Style¶
Options 里存着 dark_style 和 light_style 两份,ctx.theme() 决定当前用哪份。global_style / set_global_style / set_visuals 都只作用于当前主题那份。
| 想改 | 用 |
|---|---|
| 当前主题的 Style | ctx.global_style_mut(..) / ctx.set_global_style(..) |
| 两个主题的 Style | ctx.all_styles_mut(..) |
| 指定主题的 Style / Visuals | ctx.style_mut_of(theme, ..) / ctx.set_style_of(theme, ..) / ctx.set_visuals_of(theme, ..) |
10.6 Visuals(视觉/主题)¶
切换深色/浅色主题,用 set_theme,不是 set_visuals:
ctx.set_theme(egui::Theme::Dark);
ctx.set_theme(egui::Theme::Light);
ctx.set_theme(egui::ThemePreference::System); // 跟随系统(默认)
ThemePreference 有 Dark / Light / System 三个变体;Theme 只有 Dark / Light,并且可以直接传给 set_theme。
ctx.set_visuals(Visuals) 只是替换当前主题那份 Style 里的 visuals,不改变“当前是深色还是浅色”:
在浅色主题下
set_visuals(Visuals::dark()),只是把浅色主题那份换成了暗色配色;主题偏好、原生窗口主题(10.12)都不会跟着变。要切主题请用set_theme。
Visuals 里常用的字段:
| 字段 | 说明 |
|---|---|
dark_mode: bool |
只是“整体是深色还是浅色”的摘要,单独改它几乎没效果 |
widgets: Widgets |
各状态下控件的颜色和描边:noninteractive / inactive / hovered / active / open(下拉/菜单展开时) |
selection: Selection |
选中色:bg_fill、stroke |
window_fill / panel_fill |
窗口、面板背景 |
extreme_bg_color |
更极端的背景(输入框、滚动条等);text_edit_bg_color: Option<Color32> 可单独覆盖输入框 |
faint_bg_color |
和背景只差一点的颜色,用于 Grid::striped 等隔行色 |
hyperlink_color、warn_fg_color、error_fg_color、code_bg_color |
链接、警告、错误、代码背景色 |
override_text_color: Option<Color32> |
强制所有文字用同一个颜色 |
window_corner_radius、menu_corner_radius、window_shadow、window_stroke |
窗口/菜单的圆角、阴影、描边 |
image_loading_spinners: bool |
图片加载时是否显示 spinner(第九章) |
Widgets没有“禁用”状态:禁用的控件是在inactive/noninteractive的颜色上做淡化。
改某个颜色:
ctx.global_style_mut(|style| {
style.visuals.widgets.inactive.bg_fill = egui::Color32::from_rgb(40, 40, 40);
style.visuals.selection.bg_fill = egui::Color32::from_rgb(0, 120, 215);
});
10.7 控件视觉的 interact¶
Style::interact(&response) 返回 &WidgetVisuals,告诉你这种状态下控件该用什么颜色。写自定义控件时常用:
let visuals = ui.style().interact(&response);
ui.painter().rect(rect, egui::CornerRadius::same(4), visuals.bg_fill, visuals.bg_stroke, egui::StrokeKind::Inside);
WidgetVisuals 的字段:
| 字段 | 说明 |
|---|---|
bg_fill |
必须有背景的控件(滑块槽、复选框底)的填充,不能是透明 |
weak_bg_fill |
可以没有背景的控件(按钮)的填充,可以透明 |
bg_stroke |
外框描边 |
corner_radius |
圆角(CornerRadius) |
fg_stroke |
文字/勾/滑块把手的颜色与线宽 |
expansion |
外框向外扩多少 |
圆角参数是
CornerRadius(四个角各一个u8),不再接受f32。CornerRadius::same(4)就是四角都 4px。
interact_selectable(&response, selected) 给出选中态的视觉(返回值是 WidgetVisuals,不是引用)。
10.8 圆角(CornerRadius)¶
ui.style_mut().visuals.window_shadow = egui::Shadow::NONE; // 去掉窗口阴影
ui.style_mut().visuals.widgets.noninteractive.corner_radius = egui::CornerRadius::same(0); // 直角
CornerRadius::same(8) 是四个角都 8px(参数是 u8);也可以分别指定 nw / ne / sw / se 四个字段:
常见的圆角入口都收 impl Into<CornerRadius>,所以整数也行:
| 位置 | 写法 |
|---|---|
| 控件状态 | visuals.widgets.<状态>.corner_radius |
| 窗口 / 菜单 | visuals.window_corner_radius / visuals.menu_corner_radius |
Frame |
Frame::new().corner_radius(6) |
Button |
Button::new(..).corner_radius(6) |
Image |
Image::new(..).corner_radius(6) |
老代码里的
Rounding在 0.37 已经不存在了(从 0.32 起换成了CornerRadius),WidgetVisuals上的字段也从rounding改名corner_radius。两个变化都是硬改名,编译不过时搜这两个词就行。
10.9 自定义颜色¶
Color32 是 sRGB 8 位颜色([r, g, b, a])。常用构造:
egui::Color32::from_rgb(r, g, b) // a=255
egui::Color32::from_rgba_unmultiplied(r, g, b, a)
egui::Color32::from_rgba_premultiplied(r, g, b, a)
egui::Color32::from_gray(v) // r=g=b=v, a=255
egui::Color32::from_white_alpha(a) // 白色透明
egui::Color32::from_black_alpha(a)
另有常量(RED、WHITE、TRANSPARENT 等)和调整透明度的 color.gamma_multiply(0.5)、color.to_opaque()。
egui 内部用预乘 alpha。from_rgba_unmultiplied 会自动转换。除非写底层渲染代码,一般不用关心这个细节。
10.10 文本样式(RichText)¶
ui.label(
egui::RichText::new("Important")
.color(egui::Color32::RED)
.size(20.0)
.strong() // 更亮的颜色(不是加粗!)
.italics()
.underline()
.background_color(egui::Color32::from_rgb(60, 0, 0))
);
strong()不会加粗:它只是换成Visuals::strong_text_color()(对比度更高的颜色),weak()则是更淡的颜色。egui 的FontId里目前没有字重,也没有真正的斜体(italics()是把字形向右倾斜)。
RichText 常用方法:
| 方法 | 作用 |
|---|---|
color(c) / background_color(c) |
文字色 / 文字背景色 |
size(pt) |
字号 |
text_style(TextStyle) |
用某个预设样式(字号 + 字体族) |
heading() / small() / monospace() |
TextStyle::Heading / Small / Monospace 的快捷写法 |
code() |
等宽字体 + 代码背景色 |
strong() / weak() |
更亮 / 更淡的颜色 |
italics() / underline() / strikethrough() |
倾斜 / 下划线 / 删除线 |
raised() / small_raised() |
文字顶对齐(配合 small(),用于上标) |
family(FontFamily) |
换字体族 |
extra_letter_spacing(pt) |
额外字间距 |
line_height(Option<f32>) |
行高 |
想要真正的粗体,自己准备一个粗体字体文件,放进一个自定义名字的字体族:
let mut fonts = egui::FontDefinitions::default();
fonts.font_data.insert(
"bold".to_owned(),
std::sync::Arc::new(egui::FontData::from_static(include_bytes!(
"../assets/MyFont-Bold.ttf"
))),
);
fonts
.families
.insert(egui::FontFamily::Name("bold".into()), vec!["bold".to_owned()]);
ctx.set_fonts(fonts);
// 使用
ui.label(egui::RichText::new("真·粗体").family(egui::FontFamily::Name("bold".into())));
10.11 主题切换示例¶
impl eframe::App for MyApp {
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
egui::CentralPanel::default().show(ui, |ui| {
ui.horizontal(|ui| {
if ui.button("Dark").clicked() {
ui.ctx().set_theme(egui::Theme::Dark);
}
if ui.button("Light").clicked() {
ui.ctx().set_theme(egui::Theme::Light);
}
if ui.button("跟随系统").clicked() {
ui.ctx().set_theme(egui::ThemePreference::System);
}
});
});
}
}
egui 自带一排现成的主题按钮(深色 / 浅色 / 跟随系统,当前项高亮),一行搞定:
旧的
global_theme_preference_switch(ui)只能在深浅之间切,回不到“跟随系统”,已标#[deprecated]。
set_theme 立刻生效,下一帧就用新主题。
10.12 窗口主题同步¶
egui 支持将原生窗口主题与 egui 的主题偏好(ThemePreference)同步。启用时,每当偏好变化,egui 会给根视口发一条 ViewportCommand::SetTheme,让原生窗口装饰(标题栏、边框等)跟着变:Dark → 深色,Light → 浅色,System → 跟随系统。
// 启用窗口主题同步(默认启用)
ctx.options_mut(|o| o.sync_window_theme = true);
// 禁用窗口主题同步(如果你想自己管理原生窗口主题)
ctx.options_mut(|o| o.sync_window_theme = false);
它跟的是
set_theme设的偏好,不是Visuals的具体颜色:只调set_visuals不会改变原生标题栏。
此功能在多视口(多窗口)场景下也有效。源码:egui-0.37.0/src/context.rs 的 sync_window_theme、egui-0.37.0/src/memory/mod.rs 的 Options::sync_window_theme。
10.13 持久化样式¶
开了 eframe 的 persistence feature 后,eframe 会自动把 egui 的 Memory 存盘(App::persist_egui_memory() 默认 true),主题偏好(set_theme 的结果)和窗口位置、折叠状态等会跟着保存。
但 Options 里的 dark_style / light_style 被标了 serde(skip),所以你自定义的 Style 不会被保存,下次启动要自己再设一遍。
想让用户调过的样式下次还在:开 egui 的 serde feature(Style 才实现 Serialize / Deserialize),把 Style 存到你的 App 里,在 eframe::App::save 里写入 Storage,在 new(cc) 里读出来并 set_global_style。
10.14 小结¶
| 想改什么 | 怎么改 |
|---|---|
| 中文显示 | ctx.add_font(FontInsert::new(...)) |
| 中文/生僻字兜底 | eframe 桌面端默认已开;其他集成用 ctx.add_font_provider(Arc::new(SystemFontProvider::new()))(0.37 新增) |
| 完全换字体 | ctx.set_fonts(FontDefinitions { ... }) |
| 全局字号 | ctx.global_style_mut(\|s\| { s.text_styles.insert(TextStyle::Body, FontId::new(18.0, ...)); }) |
| 局部字号 | RichText::new(s).size(20.0) |
| 间距 | style.spacing.item_spacing = ... |
| 滚动条宽度 | style.spacing.scroll.bar_width = ... |
| 文本行间距 | style.spacing.extra_text_line_spacing = 4.0 |
| 切深/浅主题 | ctx.set_theme(Theme::Dark / Light)、ThemePreference::System |
| 换配色 | ctx.set_visuals(Visuals::dark() / light())(只换当前主题那份) |
| 选中色 | style.visuals.selection.bg_fill = ... |
| 自定义控件颜色 | style.interact(&response) 拿 WidgetVisuals |
| 强调文字 | RichText::strong()(更亮的颜色,不是粗体) |
| 窗口主题同步 | ctx.options_mut(\|o\| o.sync_window_theme = true/false) |