基于 iced 实现一个简易时钟

本文将详细介绍基于 iced 实现一个时钟的完整示例。

知识点

  • iced 的 subscription
  • 窗口图标
  • 程序图标
  • 自定义字体
  • 打包优化
  • 在 release 版本中,防止在 Windows 上出现额外的控制台窗口

预览

UI

优化后的文件大小

开发环境

  • 系统:Windows 11 专业版
  • 编辑器:Visual Studio Code
  • cargo:1.85.1 (d73d2caf9 2024-12-31)
  • 编译工具链:stable-x86_64-pc-windows-msvc (active, default)

代码

Cargo.toml

toml 复制代码
[package]
name = "clock"
version = "0.0.1"
edition = "2024"
build = "build.rs"

[dependencies]
chrono = "0.4.41" # 时间格式化
iced = { version = "0.13.1", features = ["image", "tokio"] } # image 特性是为了导入窗口图标。tokio 是为了启用 iced::time 定时器

[build-dependencies]
winres = "0.1.12" # 为可执行文件添加元信息和图标

[profile.release]
strip = true
lto = true
opt-level = "z"

build.rs

rs 复制代码
extern crate winres;

fn main() {
  if cfg!(target_os = "windows") {
    let mut res = winres::WindowsResource::new();
    res.set_icon("res/icon.ico");
    res.compile().unwrap();
  }
}

main.rs

rs 复制代码
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use std::time::Duration;

use chrono::Local;
use iced::{
    Element, Font, Length, Size, Subscription,
    widget::{column, container, text},
    window::{Icon, Settings, icon},
};

#[derive(Default)]
struct ClockApp {
    current_time: String,
}

#[derive(Debug, Clone, Copy)]
pub enum Message {
    Tick,
}

impl ClockApp {
    pub fn view(&self) -> Element<Message> {
        container(column![text(&self.current_time).size(26),])
            .center(Length::Fill)
            .into()
    }

    pub fn update(&mut self, message: Message) {
        match message {
            Message::Tick => {
                let now = Local::now();
                self.current_time =
                    format!("{} {}", now.format("%Y-%m-%d"), now.format("%H:%M:%S"));
            }
        }
    }

    fn subscription(&self) -> Subscription<Message> {
        iced::time::every(Duration::from_millis(1000)).map(|_| Message::Tick)
    }
}

fn main() -> iced::Result {
    iced::application("Clock", ClockApp::update, ClockApp::view)
        .font(include_bytes!("../res/MapleMono-Regular.ttf"))
        .default_font(Font::with_name("Maple Mono"))
        .window(Settings {
            icon: Some(Icon::from(
                icon::from_file_data(include_bytes!("../res/icon.ico"), None).unwrap(),
            )),
            size: Size::new(400.0, 200.0),
            ..Default::default()
        })
        .subscription(ClockApp::subscription)
        .run()
}

注: icon.ico 宽高是 256px * 256px

Maple Mono font

参考

zhuanlan.zhihu.com/p/167852399...

crates.io/crates/winr...

crates.io/crates/chro...

docs.rs/iced/latest...

font.subf.dev/zh-cn/downl...

相关推荐
好家伙VCC7 小时前
**发散创新:基于Rust的轻量级权限管理库设计与开源许可证实践**在现代分布式系统中,**权限控制(RBAC
java·开发语言·python·rust·开源
@atweiwei7 小时前
用 Rust 构建agent的 LLM 应用的高性能框架
开发语言·后端·rust·langchain·eclipse·llm·agent
skilllite作者7 小时前
Spec + Task 作为「开发协议层」:Rust 大模型辅助的标准化、harness 化与可回滚
开发语言·人工智能·后端·安全·架构·rust·rust沙箱
zsqw12311 小时前
以 Rust 为例,聊聊线性类型,以及整个类型系统
rust·编译器
Rust研习社11 小时前
Rust Tracing 实战指南:从基础用法到生产级落地
rust
分布式存储与RustFS12 小时前
MinIO迎来“恶龙”?RustFS这款开源存储简直“不讲武德”
架构·rust·开源·对象存储·minio·企业存储·rustfs
数据知道1 天前
claw-code 源码分析:从 TypeScript 心智到 Python/Rust——跨栈移植时类型、边界与错误模型怎么对齐?
python·ai·rust·typescript·claude code·claw code
Rust研习社1 天前
深入浅出 Rust 迭代器:从基础用法到性能优化
rust
@atweiwei1 天前
langchainrust:Rust 版 LangChain 框架(LLM+Agent+RAG)
开发语言·rust·langchain·agent·向量数据库·rag