rust 终端显示综合例程

demo程序

综合demo
各个库使用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());   // 显示,设置屏幕宽度 还有一种方式是设置显示列数
}
  1. Cell

    1)字段:

    contents:String //需要显示的内容
    width:Width		//字符串长度
    
  2. GridOption

    传递给Grid::new()网格试图的用户可分配选项

    1)字段

    direction:Direction	// 单元格写入方向
    filling:Filling		// 单元格之间的空格数
    

    direction:LeftToRight(从左到右)

    ​ TopToBottpm(从上到下)

    Filling:Spaces(Width) 空格宽度

    ​ Text(String) 字符串

  3. gird

    使用网格选项来格式化单元格所需的一切

    1)方法:

    // 创建新的网格视图
    fn new(options: GridOptions) -> Self
    
    // 在向量中保留空间以容纳要添加的给定数量的额外单元
    fn reserve(&mut self, additional: usize)
    
    // 讲一个单元格添加至向量
    fn add(&mut self, cell: Cell)
    
    // 返回可现实的网格,该网格已被打包以适合给定的宽度和最少的行数。
    // None如果任何单元格的宽度大于最大宽度,则返回。
    
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值