rust语言 (1.88) egui (0.32.1) 学习笔记(逐行注释)(一)基本代码

Cargo.toml

toml 复制代码
[dependencies]
eframe = "0.32.1"
egui = "0.32.1"

‌启动函数一:run_simple_native

  • 简化版入口函数,适用于快速原型开发
  • 仅需提供应用标题和 UI 渲染闭包即可运行
  • 典型使用场景:单面板工具、简单演示程序
rust 复制代码
// 导入egui核心库和eframe框架(eframe是egui的本地窗口封装)
use eframe::egui;

// 主函数返回Result类型以处理可能的错误
fn main() -> eframe::Result<()> {
    // 配置原生窗口参数
    let options = eframe::NativeOptions::default();
    eframe::run_simple_native("My egui App", options, move |ctx, _frame| {
        egui::CentralPanel::default().show(ctx, |ui| {
           ui.heading("Hello from egui 0.32.1!");           // 添加一级标题
           ui.label("This is a simple window in Ubuntu.");  // 添加普通文本标签
        });
    })
}

启动函数二:‌run_native

  • 完整功能入口,支持自定义应用生命周期管理
  • 需要实现eframe::App trait的结构体
  • 典型使用场景:复杂应用、需要持久化状态的项目
rust 复制代码
// 导入egui核心库和eframe框架(eframe是egui的本地窗口封装)
use eframe::egui;

// 主函数返回Result类型以处理可能的错误
fn main() -> Result<(), eframe::Error> {
    let options = eframe::NativeOptions {   // 配置窗口的初始参数
        // 设置窗口初始大小为400x300像素
        viewport: egui::ViewportBuilder::default().with_inner_size([400.0, 300.0]),
        ..Default::default()                // 其他参数保持默认值
    };

    // 启动原生窗口应用
    eframe::run_native(
        "My egui App",                                // 窗口标题
        options,                                      // 传入配置选项
        Box::new(|_cc| Ok(Box::<MyApp>::default())),  // 创建应用实例的闭包,_cc包含创建上下文信息
    )
}

// 定义应用的主要结构体
struct MyApp{}

// 为MyApp实现Default trait以提供默认初始化
impl Default for MyApp {
    fn default() -> Self {
        Self                // 返回空结构体实例
    }
}

// 为MyApp实现eframe::App trait定义应用行为
impl eframe::App for MyApp {
    // 每帧调用的更新函数
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        egui::CentralPanel::default().show(ctx, |ui| {       // 创建中央面板(egui的主要布局组件)
            ui.heading("Hello from egui 0.32.1!");           // 添加一级标题
            ui.label("This is a simple window in Ubuntu.");  // 添加普通文本标签
        });
    }
}

选择建议

  1. 优先选择run_simple_native当:

    • 开发临时性工具
    • 无需复杂状态管理
    • 快速验证UI设计
  2. 必须使用run_native当:

    • 需要保存用户配置
    • 实现多窗口交互
    • 处理文件I/O等系统操作

两者底层均基于相同的egui渲染引擎,性能差异可以忽略。对于WebAssembly目标,对应存在run_simple_webrun_web变体。