網站首頁 編程語言 正文
1、簡介
用rust寫的一個簡單的練手的demo,一個字符串時鐘,在終端用字符串方式顯示當前時間。本質是對圖片取灰度,然后每個像素按灰度門限用星號代替灰度值,就把圖片變為由星號組成的字符型圖案。把時間字符串的每個字符按照字母和數字圖片的樣式轉換為字符,然后拼接字符圖案就實現了字符時鐘的效果。
主要用到的知識有:rust操作時間、字符串、vector,字符串和vector的轉換、string,以及讓人惱火的生命周期。對比python,rust的列表入門難度可以說是地獄級的,一會borrow、一會move,暈頭轉向。
2、用到的知識點
2.1 取utc時間
時間庫使用chrono = "0.4",獲取秒數等時間。
let five_seconds = Duration::new(5, 0); let five_seconds_and_five_nanos = five_seconds + Duration::new(0, 10); assert_eq!(five_seconds_and_five_nanos.as_secs(), 5); assert_eq!(five_seconds_and_five_nanos.subsec_nanos(), 10); let five_seconds = Duration::from_secs(5); assert_eq!(five_seconds, Duration::from_millis(5_000)); assert_eq!(five_seconds, Duration::from_micros(5_000_000)); assert_eq!(five_seconds, Duration::from_nanos(5_000_000_000)); let ten_seconds = Duration::from_secs(10); let seven_nanos = Duration::from_nanos(7); let total = ten_seconds + seven_nanos; assert_eq!(total, Duration::new(10, 7));
獲取實時utc時間。
let local:DateTime<Local>= Local::now(); println!("{:?}", local.format("%Y-%m-%d %H:%M:%S").to_string()); println!("{:?}", local.format("%a %b %e %T %Y").to_string()); println!("{:?}", local.format("%c").to_string()); println!("{:?}", local.to_string()); println!("{:?}", local.to_rfc2822()); println!("{:?}", local.to_rfc3339()); let dt = Local.with_ymd_and_hms(2020 as i32, 12, 05, 12, 0, 9).unwrap(); println!("{:?}", dt.format("%Y-%m-%d %H:%M:%S").to_string()); println!("{:?}", dt.format("%a %b %e %T %Y").to_string()); println!("{:?}", dt.format("%c").to_string()); println!("{:?}", dt.to_string()); println!("{:?}", dt.to_rfc2822()); println!("{:?}", dt.to_rfc3339());
輸出為:
"2022-12-25 23:20:03"
"Sun Dec 25 23:20:03 2022"
"Sun Dec 25 23:20:03 2022"
"2022-12-25 23:20:03.499293300 +08:00"
"Sun, 25 Dec 2022 23:20:03 +0800"
"2022-12-25T23:20:03.499293300+08:00"
"2020-12-05 12:00:09"
"Sat Dec 5 12:00:09 2020"
"Sat Dec 5 12:00:09 2020"
"2020-12-05 12:00:09 +08:00"
"Sat, 05 Dec 2020 12:00:09 +0800"
"2020-12-05T12:00:09+08:00"
獲取當前時間,如下格式化為20:15:23類似的格式。
let curdate = Local::now(); let datecollect = curdate.format("%H:%M:%S").to_string();
2.2 圖片變換為像素圖案
1、讀取圖片
先準備每個數字的圖片,然后讀取圖片,轉換為灰度表示。
let cur_dir = std::env::current_dir().unwrap(). into_os_string().into_string().unwrap(); let _path = if number == ':' { format!("{}/number_pic/{}.png", &cur_dir, "maohao") } else{ format!("{}/number_pic/{}.png", &cur_dir, number) }; // println!("imagepath = {}", _path); let gray_pic = image::open(_path).unwrap() .resize(nwidth, nheight, image::imageops::FilterType::Nearest) .into_luma8();
初始化pix_clock結構體,解析需要用到的10個數字和冒號時間分隔字符。
pub struct pix_clock { words : HashMap<char, Vec<String>>, } impl pix_clock { pub fn new() -> pix_clock { let mut dict_result = HashMap::new(); let numbers = vec!['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':']; for value in numbers { let result = get_num_pic(value); dict_result.insert(value, result); // println!("num={} {:#?}", value, dict_result[&value]); } return pix_clock { words: dict_result, }; } }
2、圖片按像素灰度轉換為字符圖案
每行作為1個string字符串,按行處理,讀取完一行后把當前行的字符串push到列表,然后清空行變量,準備解析下一行的像素。每行都解析完成后,pix_data就形成了一個由nheight行,每行nwidth個字符構成的列表。
let mut pix_data: Vec<String> = vec![]; let mut line = String::from(""); for (index, tmp) in gray_pic.to_vec().iter().enumerate() { if index % nwidth as usize == 0 { if line.len()>0 { let line2 = line.clone(); pix_data.push(line2); } line.clear(); } if tmp > &gap_value { line.push_str("*"); } else { line.push_str(" "); } }
以數字3為例:println!("result data {} {:#?}", number, &pix_data);
// 輸出數據為:
result data 3 [ "*************", "*************", "****** ******", "*** ***", "*** ***", "*** *** **", "******** **", "******* ***", "**** ***", "**** ***", "******* **", "******** **", "********* **", "** *** **", "** ***", "*** ***", "***** *****", "*************", "*************", ]
2.3 字符方式顯示當前時間
上一步已經完成了單個數字轉換為字符圖案,由于時間字符串由多位數字構成,所以需要拼接圖案。例如20:15:23,就由6個數字和2個冒號組成,所以字符串“20:15:23”就需要按行合并。
1)合并每個數組的團案,而高度不變。
let time_str = datestr.chars(); // 把字符串解析為char型字符 let mut final_vector: Vec<String> = vec![]; for _index in 0..self.words.get(&'0').unwrap().len() { // 合并后的圖案高度不變,即行數不變 final_vector.push("".to_string()); // 每行的字符串變長了,先預留空String來接收每行字符 }
2)按行合并每個字符,拼接字符串的圖案
for value in time_str { //遍歷時間字符串的每個字符 let value_pix = self.words.get(&value).unwrap(); //獲取單個字符的圖案 let mut index = 0; for x in value_pix.iter() { final_vector[index].push_str(&x); # 每個字符相同行的字符串合并為一個大字符串 index += 1; } } for temp in final_vector { // 合并后的字符串,高度不變(即行數不變) println!("{}", format!("{}", temp)); // 打印合并后的字符串,按行顯示 } println!("");
2.4 時間刷新
按秒刷新,每秒計算一次圖案字符串,然后清屏后顯示,實現時間跑秒的感覺。
fn main() { let pix_clock = pix_clock::new(); let delay = time::Duration::from_secs(1); loop { let curdate = Local::now(); let datecollect = curdate.format("%H:%M:%S").to_string(); pix_clock.beautifyshow(&datecollect); thread::sleep(delay); Clear(ClearType::All); } }
原文鏈接:https://www.cnblogs.com/pingwen/p/17004872.html
相關推薦
- 2022-03-11 UE4 添加自己項目的AutomationProject,解決報錯Failed to find co
- 2022-07-22 Maven項目編譯運行后target/classes目錄下沒有xml和properties文件
- 2022-03-08 基于Redis實現阻塞隊列的方式_Redis
- 2022-12-07 iOS開發刪除storyboard步驟詳解_IOS
- 2022-11-10 Python+Selenium實現瀏覽器的控制操作_python
- 2022-05-28 python中數組和列表的簡單實例_python
- 2022-06-17 C#關鍵字in、out、ref的作用與區別_C#教程
- 2023-04-04 numpy中的norm()函數求范數實例_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支