rust GUI库——egui初体验(一)本文为egui系列的第一篇。本文旨在从零开始介绍如何使用egui构建一个本地应
前言
本文为egui系列的第一篇。旨在从零开始介绍egui的使用。因为egui的官方文档不太多,在此记录一下,方便自己也方便未来学习的人。
开发环境
- egui=0.29.1
- windows 11
- rust 1.81.0
Hello World
1.环境
# 创建一个rust项目
cargo new picpic
# 安装依赖
cargo add eframe
查看Cargo.toml文件中的内容
[package]
name = "picpic"
version = "0.1.0"
edition = "2021"
[dependencies]
eframe = "0.29.1"
2.Hello world程序
下面是一个简单的egui程序,包括设置窗口大小,在程序面板中添加一些基本元素等。
#![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()
};
// Our application state:
let mut name = "Aspirin".to_owned();
let mut age = 18;
eframe::run_simple_native("picpic", options, move |ctx, _frame| {
egui::CentralPanel::default().show(ctx, |ui| {
ui.heading("picpic");
ui.horizontal(|ui| {
let name_label = ui.label("Your name: ");
ui.text_edit_singleline(&mut name)
.labelled_by(name_label.id);
});
ui.add(egui::Slider::new(&mut age, 0..=120).text("age"));
if ui.button("Increment").clicked() {
age += 1;
}
ui.label(format!("Hello '{name}', age {age}"));
});
})
}
3.程序截图
确保所需依赖安装好以后,启动程序可以看到如下页面的程序
4.打包
在执行上述步骤以后,会在picpic/target/debug
目录下发现一个名为picpic.exe 的程序,如果双击打开程序,会发现跟随程序一起启动的还有一个终端窗口,如下。
如果要去除终端窗口需要使用
cargo build --release
命令重新打包。此时会在picpic/target/release
目录下重新生成一个picpic.exe 程序打开该程序就会发现,此时已经没有终端窗口了
总结
到目前为止,已经完成了一个简单桌面程序的创建和发布,但是目前还存在一些问题。比如默认不支持中文,代码都在main方法中可维护性有些差。下篇文章将对这些问题进行改进。
转载自:https://juejin.cn/post/7420343712871579689