跳转到内容

主题

Theme 包含决定应用外观的一组值:颜色、字号、圆角、间距和过渡时长。所有内置组件的外观都取自主题。自定义样式同样从主题取值时,外观切换和主题修改会作用于整个界面。

CPUI 内置两套主题:Theme::light() 和 Theme::dark()。Options::appearance 决定窗口使用哪一套:

取值 行为
Appearance::System(默认) 跟随系统,系统切换时界面一起切换
Appearance::Light 始终浅色
Appearance::Dark 始终深色

窗口标题栏的深浅色与外观一致。运行时切换外观使用 ui.set_appearance(见第 5.3 节)。

use cpui::{App, Appearance, Options, Ui};
struct Reader;
impl App for Reader {
fn ui(&mut self, ui: &mut Ui<'_>) {
ui.text("始终使用深色主题。");
}
}
fn main() -> Result<(), cpui::Error> {
cpui::run(Options::new("阅读器").appearance(Appearance::Dark), Reader)
}

颜色按用途命名,而非按色相命名。底色与其上文字的颜色成对出现,命名为 x 和 x_foreground:

字段 用途
background、foreground 窗口背景;正文
surface 卡片、输入框等浮在窗口背景之上的底色
muted、muted_foreground 浅底色(悬停、分组、面板);次要文字和占位提示
border、border_strong 分隔线和边框;悬停时更明显的边框
accent、accent_hover、accent_active、accent_foreground 强调色、它的悬停和按下状态,以及它上面的文字
secondary、secondary_foreground 中性按钮及其文字
danger、danger_hover、danger_active、danger_foreground 危险操作、它的悬停和按下状态,以及它上面的文字
success、success_foreground、warning、warning_foreground 成功和警告状态,用于徽章和提示条
ring 焦点环
shadow、scrim 阴影;对话框后面的遮罩
tooltip、tooltip_foreground 提示的底色和文字
selection 选中文字的底色

其他值:

字段 用途
font_size、font_size_sm、font_size_heading、font_size_title 正文、说明、标题、大标题的字号:macOS 上与系统界面一致,为 13、11、17、22;其他平台为 14、12、18、24
radius_sm、radius、radius_lg 圆角:各种行、复选框和标签;按钮、输入框、菜单和下拉框;卡片、对话框和 toast
control_height_sm、control_height、control_height_lg 小号、普通、大号的按钮、输入框和下拉框的高度(默认 24、32、40)。标签栏使用 control_height
row_height 菜单、下拉框、列表、表格、树、侧边栏和手风琴中每一行的高度(默认 28)。字号增大时行高随之增加
spacing 基准间距,其他间距是它的倍数
motion 悬停、切换等过渡的时长,单位为秒(默认 0.12)。展开、折叠区块和打开、关闭对话框的时长为它的 5/3。设为 0 关闭过渡
disabled_opacity 停用组件的不透明度,默认 0.5

控件内部的水平留白由 spacing 计算得出,因此同一尺寸的控件高度相同,主题改变后比例保持不变。各种行的左右留白均为 8 像素。

所有可通过键盘聚焦的组件都显示相同的 3 像素 ring,其圆角与组件一致。复选框、单选框和开关的焦点环只围绕框本身,不包括文字。

ui.theme() 返回当前主题的副本。须在链式设置开始之前调用,因为链式设置会借用 ui:

use cpui::Ui;
fn notice(ui: &mut Ui<'_>, text: &str) {
let t = ui.theme();
let tint = t.background.mix(t.accent, 0.12);
let notice = ui.row().w_fill().p(t.spacing * 1.5).gap(t.spacing).bg(tint);
notice.border(1, t.accent).rounded_md().children(|ui| {
ui.text(text).text_color(t.accent);
});
}

需要介于两种主题色之间的颜色时,用 Color::mix 混合,而不是写固定色值。这样颜色会随主题变化:上例的底色在深色主题下是深色背景上的一层淡强调色。

以下方法直接读取主题:

  • 文字:.muted() 使用次要文字颜色,.text_sm() 使用说明字号;ui.heading 和 ui.title 使用标题和大标题字号。
  • 形状:.rounded_md() 和 .shadow_md() 使用主题的圆角和阴影。
  • 徽章和提示条:.success()、.warning()、.danger()。
  • 容器:.bordered() 添加标准边框,.bg_muted() 和 .bg_surface() 设置 muted 和 surface 底色。

在画布中用 Painter::theme 读取主题:

use cpui::{Rect, Ui};
fn meter(ui: &mut Ui<'_>, fraction: f32) {
ui.canvas(160, 8).paint(|p| {
let (w, h) = p.size();
let (track, fill) = (p.theme().muted, p.theme().accent);
p.rounded(Rect::new(0.0, 0.0, w, h), h / 2.0, track);
p.rounded(Rect::new(0.0, 0.0, w * fraction, h), h / 2.0, fill);
});
}
组件 用到的主题值
按钮(默认) secondary、secondary_foreground、radius
主要按钮 accent、accent_hover、accent_active、accent_foreground
边框和幽灵按钮 surface、muted、border_strong、foreground
危险按钮 danger、danger_hover、danger_active、danger_foreground
输入框 surface、border、border_strong(悬停)、accent(光标)、selection
复选框、开关 accent、accent_foreground、border_strong、radius_sm
滑块、进度条 accent、muted、surface
徽章、提示条 muted 和 foreground,或 accent、success、warning、danger 的淡色底配同色文字
卡片 surface、border、radius_lg、shadow
弹出面板、对话框 surface、border、radius_lg、shadow;对话框另用 scrim
提示 tooltip、tooltip_foreground
文字、图标 默认 foreground,或所在容器设定的颜色
焦点环(所有组件) ring

停用的组件整体变淡,没有单独的颜色。

应用提供一套浅色主题和一套深色主题,CPUI 按当前外观选用其中一套。

常用的调整各有对应的方法:

  • with_base_color(BaseColor::Slate) 更换灰色系:背景、文字、边框和浅色填充。可选 Neutral、Stone、Zinc(默认)、Gray 和 Slate;深色主题使用所选灰色系的深色色阶。
  • with_accent(颜色) 更换强调色。悬停、按下、焦点环和选中文字的颜色均由它计算得出。强调色上的文字按强调色的明暗取黑色或白色。
  • with_font_size(字号) 设置正文字号,在所有平台上相同。说明、标题、大标题的字号按相同比例缩放并取整。控件和行的高度按 14 px 以内的文字设计:字号更大时随之增高,更小时保持不变。
  • with_radius(圆角) 设置控件圆角,小圆角和大圆角由它计算得出。设为 0 即为直角。
  • compact() 将控件和行的高度降低约八分之一,间距缩小四分之一,字号不变。适用于需要显示大量内容的工具。

macOS 上的字号小一号,所以在 macOS 上刚好放得下的布局,到 Windows 和 Linux 上可能换行或被截断。请在 14 px 下也检查一遍,或者用 with_font_size 让所有平台使用同一字号。

use cpui::{App, Color, Options, Theme, Ui};
struct Notes;
impl App for Notes {
fn ui(&mut self, ui: &mut Ui<'_>) {
ui.button("新建");
}
}
fn main() -> Result<(), cpui::Error> {
let accent = Color::hex(0x16a34a);
let tune = |t: Theme| t.with_accent(accent).with_font_size(15.0).with_radius(8.0).compact();
let (light, dark) = (tune(Theme::light()), tune(Theme::dark()));
cpui::run(Options::new("笔记").themes(light, dark), Notes)
}

应用只有一种外观时,使用 Options::theme(主题)。浅色和深色外观都使用这套主题,外观设置不再影响界面。

主题是普通的结构体,其他值通过字段设置:

use cpui::{Color, Theme};
let rounded = Theme {
radius: 10.0,
radius_lg: 16.0,
muted: Color::hex(0xeef2ff),
motion: 0.0,
..Theme::light().with_accent(Color::hex(0x4f46e5))
};
assert_eq!(rounded.spacing, Theme::light().spacing);
assert!(!rounded.is_dark());

直接设置 accent 字段时,需同时设置 accent_hover、accent_active、ring 和 selection,否则悬停和焦点仍使用原来的颜色。with_accent 会更新所有这些值。

应用可以在运行时修改外观和主题。当前帧按新主题重新生成后再显示,颜色在 motion 两倍的时长内渐变(尺寸立即改变)。修改对应用的所有窗口生效。

use cpui::{Appearance, Color, Theme, Ui};
struct Look {
appearance: Appearance,
green: bool,
}
fn look(ui: &mut Ui<'_>, look: &mut Look) {
let options = [
(Appearance::System, "跟随系统"),
(Appearance::Light, "浅色"),
(Appearance::Dark, "深色"),
];
if ui.select(&mut look.appearance, &options).changed() {
ui.set_appearance(look.appearance);
}
if ui.switch(&mut look.green, "绿色强调色").changed() {
let accent = Color::hex(if look.green { 0x16a34a } else { 0x2563eb });
let light = Theme::light().with_accent(accent);
let dark = Theme::dark().with_accent(accent);
ui.set_themes(light, dark);
}
}

ui.set_theme(theme) 让浅色和深色外观使用同一套主题。ui.theme().is_dark() 返回当前主题是否为深色,例如用于选择配套的图片。

theme 示例(cargo run --release -p cpui --example theme)是一个完整的程序。它可以切换外观、强调色、字号、圆角和密度,其中的色块是一个自绘组件。

直接驱动 Context 时(用于测试、截图或自定义事件循环),它提供同名的方法,并且需要显式告知系统当前是否为深色模式:

use cpui::{Appearance, Color, Context, Theme};
let accent = Color::hex(0x16a34a);
let mut ctx = Context::new(Theme::light());
ctx.set_themes(
Theme::light().with_accent(accent),
Theme::dark().with_accent(accent),
);
ctx.set_system_dark(true);
assert!(ctx.theme().is_dark());
ctx.set_appearance(Appearance::Light);
assert!(!ctx.theme().is_dark());

界面默认使用系统字体。Options::font 向后备字体列表添加一个字体。某个字体缺少字符时,依次使用列表中后面的字体:

use cpui::{FontSpec, Options};
let options = Options::new("编辑器")
.font(FontSpec::Name("Menlo".into()))
.font(FontSpec::Path("fonts/Custom.ttf".into()));

指定字体有四种方式:

  • FontSpec::Name 按字体名或字族名查找已安装的字体。
  • FontSpec::Path 加载字体文件。
  • FontSpec::Bytes 使用嵌入程序的字体。
  • FontSpec::Generic 选用系统中某一通用字族的字体,例如 GenericFamily::Serif。

Options::mono_font 以相同方式设置等宽字体,等宽文字用 ui.text(…).mono() 绘制。

文字有九档具名字重,从 .font_thin() 到 .font_black()。其他字重使用 .font_weight(FontWeight(650)):

use cpui::Ui;
fn weights(ui: &mut Ui<'_>) {
ui.text("说明").font_light();
ui.text("标签").font_medium();
ui.text("标题").font_semibold();
ui.text("合计").font_bold();
}

CPUI 尽量从字体本身取得字重:可变字体的字重轴,或同一字族中最接近的字体。字体达不到所需字重时,CPUI 加粗笔画以补足差距;笔画只会加粗,不会变细。斜体使用字体自带的斜体,字体没有斜体时将字形倾斜。

6.1 字重、语言和其他用途的字体

Section titled “6.1 字重、语言和其他用途的字体”

上述两个方法未涵盖的设置,通过将完整的 FontSet 传给 Options::fonts 完成:

use cpui::{FontSet, FontSpec, FontStack, FontWeight, FontWeights, Options, Ui};
let mut fonts = FontSet::default();
fonts.ui.push(FontSpec::Name("Inter".into()));
fonts.weights = FontWeights::uniform(FontWeight(450));
fonts.cjk_language = Some("ja".into());
let body = fonts.add(FontStack::proportional(vec![FontSpec::Name("Georgia".into())]));
let options = Options::new("阅读器").fonts(fonts);
let article = move |ui: &mut Ui<'_>| {
ui.text("使用正文字体").font(body);
};
  • weights 设置常规文字的字重,取值 100 到 900,界面字体和等宽字体各有一个值。文字上设置的字重是相对该值的偏移:如上例设为 450 时,.font_bold() 按 750 绘制。
  • cjk_language 决定汉字使用的字形,部分汉字在中文、日文和韩文中写法不同。未设置时跟随系统语言。
  • FontSet::add 注册一个 FontStack,即另一类文字(例如文档正文)使用的一组字体。它返回一个 FontKind,用于选用这组字体。FontKind::Math 为内置种类,用于绘制公式。

文字组件用 .font(种类) 选择字体种类。画布用 Font 绘制和测量文字,Font 包含种类、字号和样式:p.text(Font::new(body, 16.0).bold(), 位置, 文字, 颜色)。

悬停、开关、复选框和焦点的变化在 motion 设定的时长内平滑过渡。过渡期间只重绘相应的组件。将 motion 设为 0 可关闭所有过渡。

在自定义组件中,ui.animate(键, 目标) 返回一个以相同节奏趋近目标的值:

use cpui::{Rect, Ui};
fn reveal(ui: &mut Ui<'_>, open: &mut bool) {
ui.checkbox(open, "显示进度");
let t = ui.animate("reveal", if *open { 1.0 } else { 0.0 });
ui.canvas(200, 8).paint(|p| {
let accent = p.theme().accent;
p.rect(Rect::new(0.0, 0.0, 200.0 * t, 8.0), accent);
});
}