在 Rust 中使用 Piston 建立一個空白視窗並在視窗中顯示兩行文字,可以參考以下的範例程式碼。此範例會展示如何建立視窗、載入字型,並將兩行文字繪製到畫面上。
rust
extern crate piston;
extern crate piston2d_window as window;
extern crate piston2d_opengl_graphics as opengl_graphics;
extern crate find_folder;
use piston::event_loop::{EventSettings, Events};
use piston::input::{RenderEvent};
use window::{PistonWindow, WindowSettings};
use opengl_graphics::{GlGraphics, TextureSettings, GlyphCache, OpenGL};
use piston::input::RenderArgs;
fn main() {
// 使用 OpenGL 3.2 (你也可以用其他版本)
let opengl = OpenGL::V3_2;
// 建立視窗
let mut window: PistonWindow = WindowSettings::new("Piston 文字範例", [400, 200])
.graphics_api(opengl)
.exit_on_esc(true)
.build()
.unwrap();
// 載入字型資源(路徑通常放在專案目錄下的 assets)
let assets = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets").expect("找不到 assets 資料夾");
let ref font_path = assets.join("FiraSans-Regular.ttf");
let mut glyphs = GlyphCache::new(font_path, (), TextureSettings::new())
.expect("無法載入字型");
// 初始化 OpenGL 上下文
let mut gl = GlGraphics::new(opengl);
// 監聽事件
let mut events = Events::new(EventSettings::new());
while let Some(e) = events.next(&mut window) {
if let Some(args) = e.render_args() {
// 清除畫面並繪製文字
gl.draw(args.viewport(), |c, gl| {
use graphics::*;
// 清空背景
clear([1.0; 4], gl);
// 第一行文字
let text_1 = "第一行文字";
text(
[0.0, 0.0, 0.0, 1.0], // 黑色
32, // 字型大小32
text_1,
&mut glyphs,
c.transform.trans(20.0, 50.0),
gl,
).expect("無法繪製文字");
// 第二行文字
let text_2 = "第二行文字";
text(
[0.0, 0.0, 0.0, 1.0],
32,
text_2,
&mut glyphs,
c.transform.trans(20.0, 100.0),
gl,
).expect("無法繪製文字");
});
}
}
}