跳转至

第二章 快速开始

本章带你使用官方的 eframe 框架从零写一个 egui 程序。

2.1 建项目

cargo new my_egui_app
cd my_egui_app

添加依赖:

cargo add eframe
cargo add egui

egui 仍在快速迭代,每个版本都有破坏性改动。如果你的代码在某版跑不动,先看 CHANGELOG。

0.37 起最低 Rust 版本是 1.95,edition = "2024"。另外 default_fonts 不再是 egui 的默认 feature;eframe 默认仍然开着它,所以照上面的写法不会缺字体。只有你直接依赖 egui 时才需要显式加 features = ["default_fonts"]。

2.2 最短能跑的程序

src/main.rs:

// release 下隐藏控制台
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use eframe::egui;

fn main() -> eframe::Result {
    let options = eframe::NativeOptions {
        viewport: egui::ViewportBuilder::default().with_inner_size([320.0, 240.0]),
        ..Default::default()
    };

    eframe::run_native(
        "My egui App",
        options,
        Box::new(|_cc| {
            Ok(Box::<MyApp>::default())
        }),
    )
}

#[derive(Default)]
struct MyApp {
    count: i32,
}

impl eframe::App for MyApp {
    fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
        egui::CentralPanel::default().show(ui, |ui| {
            ui.heading("简易计数器");
            ui.label(format!("当前值:{}", self.count));
            ui.horizontal(|ui| {
                if ui.button("+1").clicked() {
                    self.count += 1;
                }
                if ui.button("-1").clicked() {
                    self.count -= 1;
                }
                if ui.button("重置").clicked() {
                    self.count = 0;
                }
            });
        });
    }
}

运行:

cargo run

你会看到一个 320×240 的窗口,顶部显示当前计数值,下面有 +1、-1、重置 三个按钮。

2.3 程序结构解读

整个程序只有三块:

(1)main:启动

let options = eframe::NativeOptions {
  viewport: egui::ViewportBuilder::default().with_inner_size([320.0, 240.0]),
    ..Default::default()
};

eframe::run_native(
  "计数器",
    options,
    Box::new(|_cc| { Ok(Box::<MyApp>::default())}),
    )

eframe::run_native 接三个参数:

  • 窗口标题。
  • NativeOptions:里面有 viewport,控制窗口大小、图标等。
  • 一个闭包,接收 &CreationContext(简称 cc),返回你的 App 实例。cc.egui_ctx 可以在程序启动前用来设置字体、样式等。

(2)MyApp:你的状态

#[derive(Default)]
struct MyApp {
    count: i32,
}

egui 是即时模式,它不替你存状态。你的所有数据(计数、滚动位置、输入框内容等)都得自己存。MyApp 这个结构体就是你的状态容器。

(3)impl eframe::App for MyApp:每帧调用

eframe::App 这个 trait 最关键的函数是 ui:

fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame)

它每帧都会被调用(60 FPS 或更高)。你在里面写 UI 代码。ui 参数是当前帧的根 Ui,你已经可以往里加控件了。

注意:新版的 eframe::App::ui 直接给你一个 &mut egui::Ui,并且没有 margin 和背景色。所以你一般会先套一个 CentralPanel::default().show(ui, |ui| { ... }) 来获得标准的内边距和背景。

2.4 跑网页版

想让同一份代码跑在网页上:

  1. 看 https://github.com/emilk/eframe_template 模板,里面有完整的 wasm 配置。
  2. 大致流程是:加 wasm-bindgen、trunk 或 wasm-pack,把 run_native 换成 WebRunner::new() + eframe::WebRunner::start。

具体配置看模板,不要硬背。

2.5 跑示例

egui 源码的 examples/ 目录里有几十个示例,非常值得一个个看:

cd egui-main
cargo run --example hello_world
cargo run --example hello_world_simple
cargo run --example custom_font
cargo run --example custom_3d_glow
cargo run --example images
cargo run --example popups
cargo run --example keyboard_events

完整列表见 examples/README.md。这是学 egui 最快的方式。