Drawing A Simple GUI
Let us design a classical GUI library using our new knowledge of traits and trait objects. We’ll only implement the drawing of it (as text) for simplicity.
我们的库中有许多 widget:
- “Window”:具有“title”且包含其他 widget。
Button
: has alabel
. In reality, it would also take a callback function to allow the program to do something when the button is clicked but we won’t include that since we’re only drawing the GUI.- “Label”:具有“label”。
这些 widget 将实现“Widget”trait,如下所示。
将以下代码复制到 https://play.rust-lang.org/,然后填入缺少的“draw_into”方法,以便实现“Widget”trait:
// TODO: remove this when you're done with your implementation. #![allow(unused_imports, unused_variables, dead_code)] pub trait Widget { /// Natural width of `self`. fn width(&self) -> usize; /// Draw the widget into a buffer. fn draw_into(&self, buffer: &mut dyn std::fmt::Write); /// Draw the widget on standard output. fn draw(&self) { let mut buffer = String::new(); self.draw_into(&mut buffer); println!("{buffer}"); } } pub struct Label { label: String, } impl Label { fn new(label: &str) -> Label { Label { label: label.to_owned(), } } } pub struct Button { label: Label, } impl Button { fn new(label: &str) -> Button { Button { label: Label::new(label), } } } pub struct Window { title: String, widgets: Vec<Box<dyn Widget>>, } impl Window { fn new(title: &str) -> Window { Window { title: title.to_owned(), widgets: Vec::new(), } } fn add_widget(&mut self, widget: Box<dyn Widget>) { self.widgets.push(widget); } fn inner_width(&self) -> usize { std::cmp::max( self.title.chars().count(), self.widgets.iter().map(|w| w.width()).max().unwrap_or(0), ) } } impl Widget for Label { fn width(&self) -> usize { unimplemented!() } fn draw_into(&self, buffer: &mut dyn std::fmt::Write) { unimplemented!() } } impl Widget for Button { fn width(&self) -> usize { unimplemented!() } fn draw_into(&self, buffer: &mut dyn std::fmt::Write) { unimplemented!() } } impl Widget for Window { fn width(&self) -> usize { unimplemented!() } fn draw_into(&self, buffer: &mut dyn std::fmt::Write) { unimplemented!() } } fn main() { let mut window = Window::new("Rust GUI Demo 1.23"); window.add_widget(Box::new(Label::new("This is a small text GUI demo."))); window.add_widget(Box::new(Button::new( "Click me!" ))); window.draw(); }
上述程序的输出可能非常简单,例如:
========
Rust GUI Demo 1.23
========
This is a small text GUI demo.
| Click me! |
如果要绘制对齐的文本,可以使用填充/对齐格式设置运算符。需要特别注意的是您填充不同字符(此处是“/”)的方式以及控制对齐的方式:
fn main() { let width = 10; println!("left aligned: |{:/<width$}|", "foo"); println!("centered: |{:/^width$}|", "foo"); println!("right aligned: |{:/>width$}|", "foo"); }
使用这些对齐技巧,您可以生成如下的输出内容:
+--------------------------------+
| Rust GUI Demo 1.23 |
+================================+
| This is a small text GUI demo. |
| +-----------+ |
| | Click me! | |
| +-----------+ |
+--------------------------------+