文章目录
demo程序
1 terminal_size
一个获取终端界面大小的库,支持linux、macos、windows。该库比较简洁,只有2个结构体和2个方法
// Height
pub struct Height(pub u16);
// Width
pub struct Width(pub u16);
// terminal_size
pub fn terminal_size() -> Option<(Width, Height)>
// terminal_size_using_fd
// 如果可用,则使用给定的文件描述符返回终端的大小。
// 如果给定的文件描述符不是 tty,则返回None
pub fn terminal_size_using_fd(fd: RawFd) -> Option<(Width, Height)>
使用示例
use terminal_size::{
Width, Height, terminal_size};
pub fn terminal_size_test(){
let size = terminal_size();
if let Some((Width(w), Height(h))) = size {
println!("Your terminal is {} cols wide and {} lines tall", w, h);
} else {
println!("Unable to get terminal size");
}
}
2 term_grid
该库以适合固定宽度字体的网格格式排列文本数据,并使用算法最小化所需空间
参考链接:https://docs.rs/term_grid/latest/term_grid/
示例:
use term_grid::{
Grid, GridOptions, Direction, Filling, Cell};
pub fn term_grid_test(){
let mut grid = Grid::new(GridOptions {
filling: Filling::Spaces(1), // 列与列之间的分隔
direction: Direction::LeftToRight, // 方向
});
for s in &["one", "two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten", "eleven", "twelve"]
{
grid.add(Cell::from(*s)); // 添加显示内容
}
println!("{}", grid.fit_into_width(24).unwrap()); // 显示,设置屏幕宽度 还有一种方式是设置显示列数
}
-
Cell
1)字段:
contents:String //需要显示的内容 width:Width //字符串长度
-
GridOption
传递给
Grid::new()
网格试图的用户可分配选项1)字段
direction:Direction // 单元格写入方向 filling:Filling // 单元格之间的空格数
direction
:LeftToRight(从左到右) TopToBottpm(从上到下)
Filling
:Spaces(Width) 空格宽度 Text(String) 字符串
-
gird
使用网格选项来格式化单元格所需的一切
1)方法:
// 创建新的网格视图 fn new(options: GridOptions) -> Self // 在向量中保留空间以容纳要添加的给定数量的额外单元 fn reserve(&mut self, additional: usize) // 讲一个单元格添加至向量 fn add(&mut self, cell: Cell) // 返回可现实的网格,该网格已被打包以适合给定的宽度和最少的行数。 // None如果任何单元格的宽度大于最大宽度,则返回。