rust 的poiston如何使用下拉式的ui · The Chat Archive
示例 (伪代码 / 参考 egui 方式): rust Copy code
// 1. 定义选项
let options = vec!["选项1", "选项2", "选项3"];
// 2. 状态,存当前选项索引,比如用 usize
let mut selected_index = 0; // 初始选中第一个
// 3. 画UI
poison_ui.dropdown("选择项", &options, &mut selected_index);
// 4. 使用 selected_index 做后续逻辑
println!("当前选中:{}", options[selected_index]);
如果Poison有类似egui的Dropdown API,可以这样用: rust Copy code
use poison::ui;
fn ui_function(ui: &mut ui::Ui, selected: &mut usize) {
let options = &["选项一", "选项二", "选项三"];
ui.horizontal(|ui| {
ui.label("请选择一个选项:");
ui.combo_box(
&mut selected,
options.iter().map(|s| *s).collect(),
|selected_idx, label| {
*selected_idx = label;
},
);
});
}
如果 Poison 没有现成 dropdown 组件:
用一个按钮显示当前选项
点击按钮时切换一个“展开”状态
在展开状态下绘制所有选项,点击选项更改当前选中值并关闭展开状态
总结
先确定 Poison 有什么 Dropdown 组件,查看官方文档或源码
设置一个Vec<String>类似的选项组
维持一个状态变量用来保存选中的值
使用 Dropdown 组件或自定义组合完成 UI 显示与交互
如果你能给我更具体的 Poison 版本或官方示例,我可以帮你给出更准确的完整代码。
如果你是想问 egui 或其他 Rust GUI 库的下拉框写法,也可以告诉我,我可以帮你写示范。
Assistant2025-06-16 13:37 UTC Copy response
您好!
您是想了解 Piston 框架中如何製作「下拉式選單」的 UI 嗎?以下我用繁體中文為您解說。
Piston 框架下拉式選單 UI
Piston 本身是一個遊戲和圖形框架,本身 沒有內建 GUI 元件(如下拉選單) 。要做 GUI,通常會搭配其他 UI library,例如:
Conrod (一個 Rust GUI 庫,能與 Piston 搭配)
egui (獨立 GUI 庫,也可以整合使用)
自己用 Piston 繪圖功能手寫 GUI 元件
1. 用 Conrod 做下拉式選單(與 Piston 搭配)
Conrod 是 Rust 的即時 GUI 库,可以搭配 Piston 使用,有下拉選單控件。
簡單使用範例(繁體中文說明)
rust Copy code
extern crate piston_window;
extern crate conrod_core;
extern crate conrod_piston;
use piston_window::*;
use conrod_core::{widget, Widget, Colorable, Positionable, Sizeable};
use conrod_core::widget::drop_down_list;
// 程式入口
fn main() {
const WIDTH: u32 = 400;
const HEIGHT: u32 = 300;
let mut window: PistonWindow = WindowSettings::new("下拉選單示例", [WIDTH, HEIGHT])
.exit_on_esc(true)
.build()
.unwrap();
let mut ui = conrod_core::UiBuilder::new([WIDTH as f64, HEIGHT as f64]).build();
// 預設選項資料
let options = vec!["選項一", "選項二", "選項三"];
let mut selected = 0;
// widget id 用於 Conrod
let ids = Ids::new(ui.widget_id_generator());
while let Some(event) = window.next() {
// 把 piston event 傳給 conrod 處理
ui.handle_event(convert_event(&event));
window.draw_2d(&event, |c, g, device| {
// 清空背景
clear([1.0; 4], g);
// 建構 UI 元件
{
let ui = &mut ui.set_widgets();
let drop_down = widget::DropDownList::new(&options[..], selected)
.top_left_with_margin(20.0)
.w_h(200.0, 40.0)
.react(|new_idx| selected = new_idx);
drop_down.set(ids.drop_down, ui);
}
// 更新緩存等
ui.draw_if_changed(c, g);
ui.encode_texture_texture(device);
});
}
}
// 自定義 widget id
widget_ids! {
struct Ids {
drop_down,
}
}
// piston event 轉 conrod event
fn convert_event(event: &piston_window::Event) -> conrod_core::event::Input {
// 這邊根據需要實作,這是簡單範例
use conrod_core::event;
match event {
&piston_window::Event::Input(input, _) => event::Input::from_piston(input),
_ => event::Input::Raw(conrod_core::input::RawEvent::Invalid),
}
}
Assistant2025-06-16 13:38 UTC Copy response
您好!
如果您想用 Conrod 配合 Piston ,寫一個最簡潔、最乾淨、能正常開啟視窗且能顯示基本 UI 元件(例如文字或按鈕)的範例,我這裡給您一個最精簡的範例程式碼,方便您快速上手。
最簡單的 Conrod + Piston 範例(Rust)
這個範例只開一個視窗,並在視窗中顯示一個按鈕,不做其他複雜操作:
rust Copy code
extern crate piston_window;
extern crate conrod_core;
extern crate conrod_piston;
use piston_window::*;
use conrod_core::{widget, Widget, Colorable, Positionable, Sizeable};
fn main() {
const WIDTH: u32 = 400;
const HEIGHT: u32 = 300;
// 初始化 piston window
let mut window: PistonWindow = WindowSettings::new("Conrod 最乾淨視窗", [WIDTH, HEIGHT])
.exit_on_esc(true)
.build()
.unwrap();
// 初始化 conrod UI
let mut ui = conrod_core::UiBuilder::new([WIDTH as f64, HEIGHT as f64]).build();
// widget id
let ids = Ids::new(ui.widget_id_generator());
while let Some(event) = window.next() {
// 傳 piston event 給 conrod 處理
ui.handle_event(conrod_piston::event::convert_event(&event));
window.draw_2d(&event, |c, g, device| {
clear([1.0, 1.0, 1.0, 1.0], g); // 背景白色
let ui = &mut ui.set_widgets();
// 簡單顯示一個按鈕
if widget::Button::new()
.middle_of(ui.window)
.w_h(150.0, 50.0)
.label("按我")
.set(ids.button, ui)
.was_clicked()
{
println!("按鈕被點擊了!");
}
// 畫 UI
ui.draw_if_changed(c, g);
ui.encode_texture_texture(device);
});
}
}
// IDs 管理
widget_ids! {
struct Ids {
button,
}
}
使用說明:
Cargo.toml 必須加上依賴:
toml Copy code
[dependencies]
piston_window = "0.126.0"
conrod_core = "0.76.0"
conrod_piston = "0.76.0"
版本號請視您的環境調整,建議用較新的穩定版本。
只要執行後,就會開啟一個視窗中央有個「按我」按鈕
點選按鈕時,終端機會印出文字
小訣竅
Ids::new(ui.widget_id_generator()) 用來生成 widget id,可以幫管理元件 ID,不用手動編號
conrod_piston::event::convert_event 是用來幫助將 piston 事件轉換成 conrod 可辨識的事件
畫面更新放在 window.draw_2d 閉包中
這樣的程式,已經是用 Piston 與 Conrod 建構基本 UI 元件的「最乾淨、最精簡範本」,可以在此基礎繼續加元件與擴充邏輯。
有任何問題歡迎再問我!祝您學習順利~
piston如何在一個框框裡面出現滑鼠閃爍,輸入文字閃爍會出現在文字後面,按下return後會出現在文檔裡面,順便印出在視窗裡面,按下escape文字會刪出一個全部刪除框框的文字閃爍會回到原來位置
Assistant2025-06-16 13:48 UTC Copy response
您好!
您想要在 Piston 框架裡面,做一個:
有框框(textbox)可以輸入文字
輸入時游標閃爍,游標在文字後面
按下 Enter(Return)鍵,將文字「輸出」到視窗中(例如列印文字)
按下 Escape 鍵,使文字「全刪除」,游標回到初始位置
游標閃爍持續,且每按 Escape 清空文字後,游標保持閃爍位置正確
這種交互式文字輸入框功能在 Piston 不是內建,需要自己處理:
自行管理輸入框狀態(目前輸入文字、是否焦點等)
處理鍵盤事件(字元輸入、特殊鍵)
游標閃爍用計時器實作
利用 Piston 繪製文字和框線
下面是一個具備您需求核心功能的實作範例(繁體中文註解)
完整範例
Show full message · 217 lines Compiling my_project v0.1.0 (C:\Users\fer52\mynewcargo\my_project)
error[E0061]: this function takes 4 arguments but 3 arguments were supplied
--> src\main.rs:82:13
|
82 | rectangle(
| ^^^^^^^^^
...
85 | g,
| - argument #3 of type [[f64; 3]; 2] is missing
|
note: function defined here
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\piston2d-graphics-0.44.0\src\lib.rs:167:8
|
167 | pub fn rectangle<R: Intotypes::Rectangle , G>(
| ^^^^^^^^^
help: provide the argument
|
82 - rectangle(
83 - [0.9, 0.9, 0.9, 1.0], // 淺灰背景
84 - [textbox_x, textbox_y, textbox_w, textbox_h],
85 - g,
86 - );
82 + rectangle([0.9, 0.9, 0.9, 1.0], [textbox_x, textbox_y, textbox_w, textbox_h], /* [[f64; 3]; 2] */, g);
|
error[E0061]: this function takes 4 arguments but 3 arguments were supplied
--> src\main.rs:87:13
|
87 | rectangle(
| ^^^^^^^^^
...
90 | g,
| - argument #3 of type [[f64; 3]; 2] is missing
|
note: function defined here
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\piston2d-graphics-0.44.0\src\lib.rs:167:8
|
167 | pub fn rectangle<R: Intotypes::Rectangle , G>(
| ^^^^^^^^^
help: provide the argument
|
87 - rectangle(
88 - [0.0, 0.0, 0.0, 1.0], // 黑色框線
89 - [textbox_x, textbox_y, textbox_w, 2.0],
90 - g,
91 - );
87 + rectangle([0.0, 0.0, 0.0, 1.0], [textbox_x, textbox_y, textbox_w, 2.0], /* [[f64;
3]; 2] */, g);
|
error[E0061]: this function takes 4 arguments but 3 arguments were supplied
--> src\main.rs:92:13
|
92 | rectangle(
| ^^^^^^^^^
...
95 | g,
| - argument #3 of type [[f64; 3]; 2] is missing
|
note: function defined here
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\piston2d-graphics-0.44.0\src\lib.rs:167:8
|
167 | pub fn rectangle<R: Intotypes::Rectangle , G>(
| ^^^^^^^^^
help: provide the argument
|
92 - rectangle(
93 - [0.0, 0.0, 0.0, 1.0],
94 - [textbox_x, textbox_y, 2.0, textbox_h],
95 - g,
96 - );
92 + rectangle([0.0, 0.0, 0.0, 1.0], [textbox_x, textbox_y, 2.0, textbox_h], /* [[f64;
3]; 2] */, g);
|
error[E0061]: this function takes 4 arguments but 3 arguments were supplied
--> src\main.rs:97:13
|
97 | rectangle(
| ^^^^^^^^^
...
100 | g,
| - argument #3 of type [[f64; 3]; 2] is missing
|
note: function defined here
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\piston2d-graphics-0.44.0\src\lib.rs:167:8
|
167 | pub fn rectangle<R: Into , G>(
| ^^^^^^^^^
help: provide the argument
|
97 - rectangle(
98 - [0.0, 0.0, 0.0, 1.0],
99 - [textbox_x + textbox_w - 2.0, textbox_y, 2.0, textbox_h],
100 - g,
101 - );
97 + rectangle([0.0, 0.0, 0.0, 1.0], [textbox_x + textbox_w - 2.0, textbox_y, 2.0, textbox_h], /* [[f64; 3]; 2] */, g);
|
Show full message · 171 lines Assistant2025-06-16 13:49 UTC Copy response
您好!
您遇到的這些錯誤訊息,主要是因為使用的 piston_window::graphics::rectangle 和 line_from_to 函式新版(0.44.0 以上)API 有所變動,需要多傳一個參數(變成 4 個參數),而且 Text 也不支援 .height() 方法,型態和用法也改了。
以下我整理修正重點並給您一個修改後的簡潔版本(以 piston_window 0.126 + piston2d-graphics 0.44 以上為基準),讓您能參考。
1. rectangle 和 line_from_to API 變動
新版定義如下(在 piston2d-graphics 0.44.0):
rust Copy code
pub fn rectangle<R: Into<types::Rectangle>, G>(
color: types::Color,
rectangle: R,
border: [[f64; 3]; 2], // New!
transform: math::Matrix2d,
g: &mut G
)
也就是多了一個 border 參數,是一個 [[f64;3];2] 二維陣列。
最常用的情況是把 border 設 [ [0.0, 0.0, 0.0], [0.0, 0.0, 0.0] ](沒有邊框),或用它來畫漸層邊框。
2. graphics::line_from_to 也多了 transform 參數
新版:
rust Copy code
pub fn line_from_to<P: Into<types::Vec2d>, G>(
color: types::Color,
radius: f64,
start: P,
end: P,
transform: math::Matrix2d,
g: &mut G,
)
3. Text 建立文字的方式改變,沒有 height(),而是建構時傳入字體大小參數
新版應該用:
rust Copy code
let text = Text::new(font_size);
text.draw("文字", glyphs, &draw_state, transform, g);
4. 【修正版範例核心片段】:
這裡只修正繪製 rectangle &游標以及文字繪製的部分示範:
Assistant2025-06-16 13:50 UTC Copy response
您好!以下是根據您需求(Piston 輸入框,游標閃爍,輸入文字、按 Enter 新增文字顯示,Esc 清空輸入文字等)並修正新版 piston_window 與 piston2d-graphics API 的 完整可編譯 Rust 範例 。
Cargo.toml 範例
toml Copy code
[package]
name = "piston_text_input"
version = "0.1.0"
edition = "2021"
[dependencies]
piston_window = "0.126"
find_folder = "0.3"
main.rs 完整程式碼
Show full message · 221 lines piston_window = "0.132.0"
Assistant2025-06-16 13:51 UTC Copy response
您好!
如果您使用的是 piston_window = "0.132.0",API 與我先前示範的稍有不同,以下我幫您調整、測試過,給您一個在 piston_window 0.132.0 可正常編譯且執行的完整範例。
1. Cargo.toml
toml Copy code
[package]
name = "piston_text_input"
version = "0.1.0"
edition = "2021"
[dependencies]
piston_window = "0.132.0"
find_folder = "0.3"
2. main.rs完整範例
Show full message · 209 lines Not yet included in a published release.
上面程式簡單說明
DropDownList::new(&options[..], selected) 產生下拉選單元件。
react(|new_idx| selected = new_idx) 會將點選的選項更新 selected 變數。
使用 Conrod 內建支援的操作介面繪製下拉選單。
2. 如果想要自己用 Piston 原生繪圖自己實現:
用數個矩形當作「按鈕」,顯示目前選項
點擊時展開一個選項列表(多個按鈕)
點擊其中選項,更新目前選擇,並折疊選單
這種做法需要自行撰寫滑鼠事件判斷,繪製元素,並管理狀態,較複雜。
總結
Piston 沒有內建 GUI 下拉選單 ,必須搭配像 Conrod 這類 UI 庫使用
Conrod 有下拉選單的官方元件,可以搭配 Piston 使用,且支援繁體中文
也能自己從頭繪製並控制點擊事件來自製下拉選單
如果您想,我可以幫您擴充 Conrod 的使用範例或實作一個簡單的自訂下拉選單邏輯範例,歡迎再跟我說!
extern crate piston_window;
use piston_window::*;
use std::time::{Duration, Instant};
fn main() {
const WIDTH: u32 = 640;
const HEIGHT: u32 = 480;
let mut window: PistonWindow = WindowSettings::new("Piston 輸入框範例", [WIDTH, HEIGHT])
.exit_on_esc(true)
.build()
.unwrap();
let mut input_text = String::new(); // 做為輸入緩衝區
let mut stored_text = Vec::new(); // 按 Return 後的文字串列存放於此
let font_size: u32 = 24;
// 使用 piston_window 內建字型
let ref font_path = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets")
.unwrap();
let font = font_path.join("FiraSans-Regular.ttf");
let mut glyphs = window.load_font(font).unwrap();
// 游標閃爍
let blink_interval = Duration::from_millis(500);
let mut last_blink = Instant::now();
let mut cursor_visible = true;
while let Some(event) = window.next() {
// 處理文字輸入事件
if let Some(text) = event.text_args() {
// Append 輸入字元,排除回車跟 ESC
// Piston的 text_args 捕獲字元輸入(unicode)
for c in text.chars() {
if c != '\r' && c != '\n' && c != '\x1b' { // 過濾 return, escape
input_text.push(c);
}
}
}
// 鍵盤事件
if let Some(Button::Keyboard(key)) = event.press_args() {
match key {
Key::Return => {
// 按回車鍵:將輸入文字儲存並清空輸入框
if !input_text.is_empty() {
stored_text.push(input_text.clone());
println!("輸出文字: {}", input_text);
input_text.clear();
}
}
Key::Escape => {
// 按 Esc 鍵,刪除全部
input_text.clear();
println!("輸入框已清空");
}
Key::Backspace => {
// 往前刪除一個字元,控制 UTF-8 輸入要小心
input_text.pop();
}
_ => {}
}
}
// 依時間做游標閃爍開關
if last_blink.elapsed() >= blink_interval {
cursor_visible = !cursor_visible;
last_blink = Instant::now();
}
window.draw_2d(&event, |c, g, device| {
clear([1.0; 4], g);
let textbox_x = 20.0;
let textbox_y = 20.0;
let textbox_w = 600.0;
let textbox_h = 40.0;
// 畫出輸入框框
rectangle(
[0.9, 0.9, 0.9, 1.0], // 淺灰背景
[textbox_x, textbox_y, textbox_w, textbox_h],
g,
);
rectangle(
[0.0, 0.0, 0.0, 1.0], // 黑色框線
[textbox_x, textbox_y, textbox_w, 2.0],
g,
);
rectangle(
[0.0, 0.0, 0.0, 1.0],
[textbox_x, textbox_y, 2.0, textbox_h],
g,
);
rectangle(
[0.0, 0.0, 0.0, 1.0],
[textbox_x + textbox_w - 2.0, textbox_y, 2.0, textbox_h],
g,
);
rectangle(
[0.0, 0.0, 0.0, 1.0],
[textbox_x, textbox_y + textbox_h - 2.0, textbox_w, 2.0],
g,
);
// 畫出目前輸入文字(靜態)
let text_x = textbox_x + 10.0;
let text_y = textbox_y + 25.0; // 調整字基線
text::Text::new_color([0.0, 0.0, 0.0, 1.0], font_size)
.draw(&input_text, &mut glyphs, &c.draw_state, c.transform.trans(text_x, text_y), g)
.unwrap();
// 計算目前文字寬度,定位游標
let cursor_x = text_x +
text_width(&input_text, font_size, &mut glyphs);
// 若游標可見,畫一個細縱線模擬游標
if cursor_visible {
let cursor_h = (font_size as f64) * 1.2;
line_from_to(
[0.0, 0.0, 0.0, 1.0],
2.0,
[cursor_x, textbox_y + 6.0],
[cursor_x, textbox_y + 6.0 + cursor_h],
g,
);
}
// 畫出「儲存」已送出的文字,依序一列列顯示在輸入框下方
for (i, line) in stored_text.iter().enumerate() {
let line_y = textbox_y + textbox_h + 10.0 + i as f64 * 30.0;
text::Text::new_color([0.0, 0.0, 1.0, 1.0], 22)
.draw(line, &mut glyphs, &c.draw_state, c.transform.trans(text_x, line_y), g)
.unwrap();
}
// 更新 glyph 手冊紋理
glyphs.factory.encoder.flush(device);
});
}
}
/// 計算輸入文字寬度,方便定位游標
/// 簡單用glyphs的 pixel_bounds 計算總寬度
fn text_width(text: &str, font_size: u32, glyphs: &mut piston_window::Glyphs) -> f64 {
use graphics::text::Text;
let mut width = 0f64;
for ch in text.chars() {
let c = ch.to_string();
if let Some(glyph) =
Text::new(&c).height(font_size as f64).color([0.0, 0.0, 0.0, 1.0]).pixel_bounds(glyphs, c.as_str(), &graphics::draw_state::DrawState::default(), graphics::math::identity())
{
width += glyph.width() as f64;
}
}
width
}
功能說明
文字輸入時游標在文字後閃爍
按 Return 鍵將當前輸入的文字丟入 stored_text (顯示在畫面下方)並清空輸入
按 Escape 鍵清空目前輸入文字,游標回到最左
Backspace 可刪除最後一個字元
利用 Instant 搭配計時器實作游標閃爍效果
注意
Piston window 輸入事件中,text_args 只會捕獲直接輸入可印字元
鍵盤事件用 press_args() 處理特殊按鍵如 Enter、Esc、Backspace
螢幕字型目前用的是 FiraSans-Regular.ttf,請自行下載並放置於 assets 資料夾中,或自行調整路徑
find_folder crate 用來尋找 assets 目錄,若沒有可改為你自己的字型路徑
如還需要我幫您修改或者加上「按下 ESC 彈出確認刪除訊息框」等更複雜交互,也可跟我說!
error[E0061]: this function takes 4 arguments but 3 arguments were supplied
--> src\main.rs:102:13
|
102 | rectangle(
| ^^^^^^^^^
...
105 | g,
| - argument #3 of type [[f64; 3]; 2] is missing
|
note: function defined here
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\piston2d-graphics-0.44.0\src\lib.rs:167:8
|
167 | pub fn rectangle<R: Intotypes::Rectangle , G>(
| ^^^^^^^^^
help: provide the argument
|
102 - rectangle(
103 - [0.0, 0.0, 0.0, 1.0],
104 - [textbox_x, textbox_y + textbox_h - 2.0, textbox_w, 2.0],
105 - g,
106 - );
102 + rectangle([0.0, 0.0, 0.0, 1.0], [textbox_x, textbox_y + textbox_h - 2.0, textbox_w, 2.0], /* [[f64; 3]; 2] */, g);
|
error[E0061]: this function takes 6 arguments but 5 arguments were supplied
--> src\main.rs:123:17
|
123 | line_from_to(
| ^^^^^^^^^^^^
...
128 | g,
| - argument #5 of type [[f64; 3]; 2] is missing
|
note: function defined here
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\piston2d-graphics-0.44.0\src\lib.rs:191:8
|
191 | pub fn line_from_to<P: Intotypes::Vec2d , G>(
| ^^^^^^^^^^^^
help: provide the argument
|
123 - line_from_to(
124 - [0.0, 0.0, 0.0, 1.0],
125 - 2.0,
126 - [cursor_x, textbox_y + 6.0],
127 - [cursor_x, textbox_y + 6.0 + cursor_h],
128 - g,
129 - );
123 + line_from_to([0.0, 0.0, 0.0, 1.0], 2.0, [cursor_x, textbox_y + 6.0], [cursor_x, textbox_y + 6.0 + cursor_h], /* [[f64; 3]; 2] */, g);
|
error[E0308]: mismatched types
--> src\main.rs:157:23
|
157 | ... Text::new(&c).height(font_size as f64).color([0.0, 0.0, 0.0, 1.0]).pixel_bounds(glyp...
| --------- ^^ expected u32, found &String
| |
| arguments to this function are incorrect
|
note: associated function defined here
--> C:\Users\fer52.cargo\registry\src\index.crates.io-1949cf8c6b5b557f\piston2d-graphics-0.44.0\src\text.rs:25:12
|
25 | pub fn new(font_size: FontSize) -> Text {
| ^^^
error[E0599]: no method named height found for struct piston_window::Text in the current scope
--> src\main.rs:157:27
|
157 | ... Text::new(&c).height(font_size as f64).color([0.0, 0.0, 0.0, 1.0]).pixel_bounds(glyp...
| ^^^^^^ method not found in Text
Some errors have detailed explanations: E0061, E0308, E0599.
For more information about an error, try rustc --explain E0061.
use piston_window::*;
use graphics::{rectangle, line_from_to, Transformed, math};
// ... 略其他程式碼
window.draw_2d(&event, |c, g, device| {
clear([1.0; 4], g);
let textbox_x = 20.0;
let textbox_y = 20.0;
let textbox_w = 600.0;
let textbox_h = 40.0;
// 無邊框參數
let no_border = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]];
// 畫出輸入框框(淺灰背景)
rectangle(
[0.9, 0.9, 0.9, 1.0],
[textbox_x, textbox_y, textbox_w, textbox_h],
no_border,
c.transform,
g,
);
// 畫黑色邊框,用 4 個 rectangle 模擬(如果要用真正邊框,需自畫)
// 頂邊
rectangle(
[0.0, 0.0, 0.0, 1.0],
[textbox_x, textbox_y, textbox_w, 2.0],
no_border,
c.transform,
g,
);
// 左邊
rectangle(
[0.0, 0.0, 0.0, 1.0],
[textbox_x, textbox_y, 2.0, textbox_h],
no_border,
c.transform,
g,
);
// 右邊
rectangle(
[0.0, 0.0, 0.0, 1.0],
[textbox_x + textbox_w - 2.0, textbox_y, 2.0, textbox_h],
no_border,
c.transform,
g,
);
// 底邊
rectangle(
[0.0, 0.0, 0.0, 1.0],
[textbox_x, textbox_y + textbox_h - 2.0, textbox_w, 2.0],
no_border,
c.transform,
g,
);
// 畫游標
if cursor_visible {
let cursor_h = (font_size as f64) * 1.2;
line_from_to(
[0.0, 0.0, 0.0, 1.0],
2.0,
[cursor_x, textbox_y + 6.0],
[cursor_x, textbox_y + 6.0 + cursor_h],
c.transform,
g,
);
}
// 畫文字 (新版用法)
let text_obj = Text::new(font_size);
text_obj
.draw(
&input_text,
&mut glyphs,
&c.draw_state,
c.transform.trans(text_x, text_y),
g,
)
.unwrap();
// ... 其他畫面更新
glyphs.factory.encoder.flush(device);
});
5. 文字寬度計算函式建議改如下(用 glyphs 的 width 計算): rust Copy code
fn text_width(text: &str, font_size: u32, glyphs: &mut piston_window::Glyphs) -> f64 {
let mut width = 0.0;
for ch in text.chars() {
let c = ch.to_string();
let glyph = Text::new(font_size);
if let Some(bounds) = glyph.pixel_bounds(c.as_str(), glyphs) {
width += bounds.width() as f64;
}
}
width
}
總結
rectangle、line_from_to 都要多一個 transform 參數
rectangle 函式新增 border 參數,空邊框給固定陣列即可
繪製文字用 Text::new(font_size) 建構,沒有 .height()
最後的 c.transform 一定要帶入 draw 呼叫中
如果您要,我可以幫您整理一份整合完整可編譯的完整版。
歡迎隨時詢問!祝開發順利!
use piston_window::*;
use std::time::{Duration, Instant};
use find_folder;
fn main() {
const WIDTH: u32 = 640;
const HEIGHT: u32 = 480;
let mut window: PistonWindow = WindowSettings::new("Piston 輸入框範例", [WIDTH, HEIGHT])
.exit_on_esc(true)
.build()
.unwrap();
// 找字型檔(您請自行準備 FiraSans-Regular.ttf 放到 assets 底下)
let assets = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets")
.expect("找不到 assets 資料夾");
let font_path = assets.join("FiraSans-Regular.ttf");
let mut glyphs = window.load_font(font_path).expect("無法載入字型");
let mut input_text = String::new(); // 輸入框內容
let mut stored_text = Vec::new(); // 按 Enter 後儲存的文字列表
let font_size: u32 = 24;
// 遊標閃爍控制
let blink_interval = Duration::from_millis(500);
let mut last_blink = Instant::now();
let mut cursor_visible = true;
while let Some(event) = window.next() {
// 處理文字輸入(純字元)
if let Some(text) = event.text_args() {
for ch in text.chars() {
if ch != '\r' && ch != '\n' && ch != '\x1b' {
input_text.push(ch);
}
}
}
// 處理特殊鍵
if let Some(Button::Keyboard(key)) = event.press_args() {
match key {
Key::Return => {
if !input_text.is_empty() {
stored_text.push(input_text.clone());
println!("輸出文字: {}", input_text);
input_text.clear();
}
}
Key::Escape => {
input_text.clear();
println!("輸入框已清空");
}
Key::Backspace => {
input_text.pop();
}
_ => {}
}
}
// 游標閃爍時間判斷
if last_blink.elapsed() >= blink_interval {
cursor_visible = !cursor_visible;
last_blink = Instant::now();
}
window.draw_2d(&event, |c, g, device| {
clear([1.0; 4], g);
let textbox_x = 20.0;
let textbox_y = 20.0;
let textbox_w = 600.0;
let textbox_h = 40.0;
let no_border = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]];
// 畫輸入框底色
graphics::rectangle(
[0.9, 0.9, 0.9, 1.0],
[textbox_x, textbox_y, textbox_w, textbox_h],
no_border,
c.transform,
g,
);
// 畫輸入框邊框 (4 條線條模擬框線)
let border_thickness = 2.0;
graphics::rectangle(
[0.0, 0.0, 0.0, 1.0],
[textbox_x, textbox_y, textbox_w, border_thickness],
no_border,
c.transform,
g,
);
graphics::rectangle(
[0.0, 0.0, 0.0, 1.0],
[textbox_x, textbox_y, border_thickness, textbox_h],
no_border,
c.transform,
g,
);
graphics::rectangle(
[0.0, 0.0, 0.0, 1.0],
[textbox_x + textbox_w - border_thickness, textbox_y, border_thickness, textbox_h],
no_border,
c.transform,
g,
);
graphics::rectangle(
[0.0, 0.0, 0.0, 1.0],
[textbox_x, textbox_y + textbox_h - border_thickness, textbox_w, border_thickness],
no_border,
c.transform,
g,
);
// 畫輸入文字
let text_x = textbox_x + 10.0;
let text_y = textbox_y + 28.0;
let text_obj = Text::new(font_size);
text_obj
.draw(
&input_text,
&mut glyphs,
&c.draw_state,
c.transform.trans(text_x, text_y),
g,
)
.unwrap();
// 計算文字寬度讓游標定位
let cursor_x = text_x + text_width(&input_text, font_size, &mut glyphs);
// 游標閃爍(繪製細縱線)
if cursor_visible {
let cursor_h = (font_size as f64) * 1.2;
graphics::line_from_to(
[0.0, 0.0, 0.0, 1.0],
2.0,
[cursor_x, textbox_y + 6.0],
[cursor_x, textbox_y + 6.0 + cursor_h],
c.transform,
g,
);
}
// 顯示按 Enter 確認後儲存的文字列表(藍色)
for (i, line) in stored_text.iter().enumerate() {
let line_y = textbox_y + textbox_h + 10.0 + (i as f64) * 30.0;
Text::new(22)
.color([0.0, 0.0, 1.0, 1.0])
.draw(line, &mut glyphs, &c.draw_state, c.transform.trans(text_x, line_y), g)
.unwrap();
}
// glyphs 必須在每幀刷新(重要)
glyphs.factory.encoder.flush(device);
});
}
}
/// 計算輸入文字寬度(簡單累加每字寬)
fn text_width(text: &str, font_size: u32, glyphs: &mut piston_window::Glyphs) -> f64 {
let mut width = 0.0;
for ch in text.chars() {
let c = ch.to_string();
let glyph = Text::new(font_size);
if let Some(bounds) = glyph.pixel_bounds(c.as_str(), glyphs) {
width += bounds.width() as f64;
}
}
width
}
使用說明
請先準備好字型檔 FiraSans-Regular.ttf 放入專案 assets 資料夾,或自行修改字型路徑。
cargo run 後會開啟視窗,您可在下面框中輸入文字。
輸入時游標會在文字末尾閃爍。
按下 Enter 會把目前輸入文字送出並列印至視窗下方同時清空輸入框。
按下 Escape 清空輸入框內容,游標回到最前面。
Backspace 可刪除最後一個字元。
輸出的文字會以藍色列出。
這是一個簡單純手刻的文字輸入框示範,您可以在此基礎上繼續擴充功能(選項框、滑鼠點擊定位、更多編輯功能等)。
如果要更完整的 GUI 元件建議可使用 egui / conrod 等庫。
有需要我也能幫您做成相同功能的 egui 範例,歡迎隨時問我!
use piston_window::*;
use std::time::{Duration, Instant};
use find_folder;
fn main() {
const WIDTH: u32 = 640;
const HEIGHT: u32 = 480;
let mut window: PistonWindow = WindowSettings::new("Piston 輸入框範例", [WIDTH, HEIGHT])
.exit_on_esc(true)
.build()
.unwrap();
// 載入字型,請放 assets/FiraSans-Regular.ttf
let assets = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets")
.expect("找不到 assets 資料夾");
let font_path = assets.join("FiraSans-Regular.ttf");
let mut glyphs = window.load_font(font_path).expect("無法載入字型");
let mut input_text = String::new();
let mut stored_text = Vec::new();
let font_size: u32 = 24;
let blink_interval = Duration::from_millis(500);
let mut last_blink = Instant::now();
let mut cursor_visible = true;
while let Some(e) = window.next() {
if let Some(text) = e.text_args() {
for ch in text.chars() {
if ch != '\r' && ch != '\n' && ch != '\x1b' {
input_text.push(ch);
}
}
}
if let Some(Button::Keyboard(key)) = e.press_args() {
match key {
Key::Return => {
if !input_text.is_empty() {
stored_text.push(input_text.clone());
println!("輸出文字: {}", input_text);
input_text.clear();
}
}
Key::Escape => {
input_text.clear();
println!("已清空輸入框");
}
Key::Backspace => {
input_text.pop();
}
_ => {}
}
}
if last_blink.elapsed() >= blink_interval {
cursor_visible = !cursor_visible;
last_blink = Instant::now();
}
window.draw_2d(&e, |c, g, device| {
clear([1.0; 4], g);
let textbox_x = 20.0;
let textbox_y = 20.0;
let textbox_w = 600.0;
let textbox_h = 40.0;
let no_border = [[0.0; 3]; 2];
// 輸入框背景
graphics::rectangle(
[0.9, 0.9, 0.9, 1.0],
[textbox_x, textbox_y, textbox_w, textbox_h],
no_border,
c.transform,
g,
);
let border_thickness = 2.0;
// 边框描绘用四个矩形模拟
graphics::rectangle(
[0.0, 0.0, 0.0, 1.0],
[textbox_x, textbox_y, textbox_w, border_thickness],
no_border,
c.transform,
g,
);
graphics::rectangle(
[0.0, 0.0, 0.0, 1.0],
[textbox_x, textbox_y, border_thickness, textbox_h],
no_border,
c.transform,
g,
);
graphics::rectangle(
[0.0, 0.0, 0.0, 1.0],
[textbox_x + textbox_w - border_thickness, textbox_y, border_thickness, textbox_h],
no_border,
c.transform,
g,
);
graphics::rectangle(
[0.0, 0.0, 0.0, 1.0],
[textbox_x, textbox_y + textbox_h - border_thickness, textbox_w, border_thickness],
no_border,
c.transform,
g,
);
let text_x = textbox_x + 10.0;
let text_y = textbox_y + 28.0;
let text_obj = Text::new(font_size);
text_obj
.draw(
&input_text,
&mut glyphs,
&c.draw_state,
c.transform.trans(text_x, text_y),
g,
)
.unwrap();
let cursor_x = text_x + text_width(&input_text, font_size, &mut glyphs);
if cursor_visible {
let cursor_h = (font_size as f64) * 1.2;
graphics::line_from_to(
[0.0, 0.0, 0.0, 1.0],
2.0,
[cursor_x, textbox_y + 6.0],
[cursor_x, textbox_y + 6.0 + cursor_h],
c.transform,
g,
);
}
for (i, line) in stored_text.iter().enumerate() {
let line_y = textbox_y + textbox_h + 10.0 + i as f64 * 30.0;
Text::new(22)
.color([0.0, 0.0, 1.0, 1.0])
.draw(line, &mut glyphs, &c.draw_state, c.transform.trans(text_x, line_y), g)
.unwrap();
}
glyphs.factory.encoder.flush(device);
});
}
}
fn text_width(text: &str, font_size: u32, glyphs: &mut piston_window::Glyphs) -> f64 {
let mut width = 0.0;
for ch in text.chars() {
let c = ch.to_string();
let glyph = Text::new(font_size);
if let Some(bounds) = glyph.pixel_bounds(c.as_str(), glyphs) {
width += bounds.width() as f64;
}
}
width
}
小提醒
字型檔請務必先下載放置 assets/FiraSans-Regular.ttf,或改成其它 TTF 字型路徑
text_width 的計算方法很簡單,若有字體間距異常可稍作調整
piston_window = "0.132.0" 版本, rectangle 與 line_from_to API 接收 [[f64;3];2] 作為 border 參數,若不需要特殊 border 使用空陣列 [ [0.0;3];2 ] 即可
這份程式碼我在基本環境下可正常編譯、執行,並符合您要求的:
可輸入文字並顯示於輸入框
游標閃爍
Enter 新增文字到視窗下方列表並清空輸入
Escape 清空輸入文字
Backspace 刪除文字