Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIAi2 WildChat-4.8M (AI2)

如何利用rust 把一張圖變成windows 95風格的點陣圖

  1. User

    如何利用rust 把一張圖變成windows 95風格的點陣圖

  2. Assistant

    要用 Rust 把一張圖片轉成 Windows 95 風格的點陣圖(像素化且配色有限),你可以按照以下步驟來做:

    1. 載入圖片
    2. 縮小解析度(像素化 pixelate)
    3. 降低色彩數量(quantize 量化調色盤)
    4. 保存結果圖片

    Windows 95 的點陣圖風格通常有以下特點:

    • 限制的調色盤(通常是擁有16色或256色的調色盤)
    • 顯著的像素感(像素塊大,邊界清晰)

    使用的 Rust 套件

    • image:讀寫及處理圖片
    • palette:色彩相關處理(量化時可用)
    • imageproc:附加的圖片處理工具

    以下範例示範基本流程:


    範例程式碼

    Cargo.toml:

    [dependencies]
    image = "0.24"
    palette = "0.6"
    

    main.rs:

    use image::{io::Reader as ImageReader, GenericImageView, ImageBuffer, Rgba};
    use palette::{Pixel, Srgb};
    use std::path::Path;
    
    fn main() {
        // 載入圖片
        let img = ImageReader::open("input.png").unwrap().decode().unwrap();
    
        // pixelate 設定
        let pixel_size = 8;
    
        // 縮小圖片大小(以 pixel_size 為單位縮小)
        let (width, height) = img.dimensions();
        let small_width = width / pixel_size;
        let small_height = height / pixel_size;
    
        let small_img = img.resize_exact(small_width, small_height, image::imageops::FilterType::Nearest);
    
        // 量化 - 把每個像素顏色限制到 Windows 95 調色盤
        // Windows 95 16色調色盤(來自網路資料,作為範例)
        let win95_palette: [Rgba<u8>; 16] = [
            Rgba([0, 0, 0, 255]),           // Black
            Rgba([0, 0, 128, 255]),         // Navy
            Rgba([0, 128, 0, 255]),         // Green
            Rgba([0, 128, 128, 255]),       // Teal
            Rgba([128, 0, 0, 255]),         // Maroon
            Rgba([128, 0, 128, 255]),       // Purple
            Rgba([128, 128, 0, 255]),       // Olive
            Rgba([192, 192, 192, 255]),     // Silver
            Rgba([128, 128, 128, 255]),     // Gray
            Rgba([0, 0, 255, 255]),         // Blue
            Rgba([0, 255, 0, 255]),         // Lime
            Rgba([0, 255, 255, 255]),       // Aqua
            Rgba([255, 0, 0, 255]),         // Red
            Rgba([255, 0, 255, 255]),       // Fuchsia
            Rgba([255, 255, 0, 255]),       // Yellow
            Rgba([255, 255, 255, 255]),     // White
        ];
    
        // 簡單函式,從調色盤中找最近顏色
        fn nearest_color(color: Rgba<u8>, palette: &[Rgba<u8>]) -> Rgba<u8> {
            palette.iter()
                .min_by_key(|c| {
                    let dr = c[0] as i32 - color[0] as i32;
                    let dg = c[1] as i32 - color[1] as i32;
                    let db = c[2] as i32 - color[2] as i32;
                    dr * dr + dg * dg + db * db
                })
                .copied()
                .unwrap_or(color)
        }
    
        // 建立 pixelated 並量化調色盤的圖
        let mut quantized_img = ImageBuffer::new(small_width, small_height);
        for (x, y, pixel) in small_img.pixels() {
            let quant_color = nearest_color(pixel, &win95_palette);
            quantized_img.put_pixel(x, y, quant_color);
        }
    
        // 放大回原始大小(放大時用最鄰近法保持像素感)
        let pixelated_img = image::imageops::resize(
            &quantized_img,
            width,
            height,
            image::imageops::FilterType::Nearest,
        );
    
        // 儲存結果
        pixelated_img.save("output_win95.png").unwrap();
    
        println!("已完成 Windows 95 風格點陣圖的轉換");
    }
    

    執行結果說明

    • 先從原圖縮小成 pixel_size 大小,例如改成每 8x8 pixel 合併成 1 pixel
    • 再透過調色盤量化把顏色減成 Windows 95 16色
    • 最後再放大回原圖大小,但放大時用最近鄰插值法讓畫面保持像素感
    • 輸出時檔名用 output_win95.png

    自訂擴充

    • 你可以調整 pixel_size 來改變像素格大小
    • 你可以自訂調色盤,Windows 95 也有 256 色調色盤可以用,更接近系統風格
    • 若希望更精緻可以考慮使用專門的調色盤量化演算法(像 k-means、MMCQ 等),Rust 有相關 crates 也支持

    如有需要我可以協助提供更複雜的量化方法範例!

  3. User

    上面可以結合pistoon嗎?把所有數值弄成可調式在一個畫面裡面,然後可以把所有數值存起來,然後我可以依照喜好讀取不同的數值,,然後有讀取照片按鈕,然後轉檔按鈕

  4. Assistant

    你說的「pistoon」我推測是指 Rust 的 GUI 庫 Piston(一個 2D 渲染和 GUI 生態系),希望做一個 GUI 工具,包含:

    • 可調整參數(pixel size、調色盤、色彩數量等)
    • 參數保存和載入(用檔案儲存設定)
    • 讀取圖片按鈕
    • 轉檔按鈕,並顯示結果

    框架建議 & 簡單說明

    1. GUI 库選擇

    Rust 目前做 GUI 的生態有幾個選擇:

    • Piston:Piston 本身比較偏向遊戲引擎和 2D繪圖,GUI 介面需要搭配其他庫(如 conrod/tiny-skia 等)
    • iced:目前頗受歡迎且易用,支援按鈕、輸入框、檔案選擇器等
    • egui:即時GUI,快速、輕量
    • GTK (通過 gtk-rs):完整的桌面 GUI 支援
    • 其他(比如 druid、fltk)

    如果你沒特別指定,但想快速做出調整參數的UI,iced 或 egui 會更簡單且生態完善。


    2. 功能概覽

    • File Open 按鈕 → 開啟圖片
    • 數值輸入(pixel size 等) → Slider or TextInput 控制參數
    • 保存/載入設定 → 將參數序列化成檔案(JSON/TOML)讀寫
    • 轉換按鈕 → 執行點陣化程序並將圖片儲存或預覽

    以 iced 為例簡單示範架構


    範例程式架構示意

    Cargo.toml(新增.ui packages)

    [dependencies]
    image = "0.24"
    palette = "0.6"
    iced = {version = "0.9", features = ["canvas", "image"]}
    serde = {version = "1.0", features=["derive"]}
    serde_json = "1.0"
    rfd = "0.11" # 用於跨平台檔案對話視窗
    

    main.rs(核心流程+GUI簡化版本)

    use iced::{
        button, executor, Application, Button, Clipboard, Color, Column, Command,
        Container, Element, Length, Row, Settings, Slider, Text, TextInput,
    };
    use iced_native::image::Handle;
    use iced_native::widget::Image;
    use rfd::FileDialog;
    use serde::{Deserialize, Serialize};
    use std::path::PathBuf;
    use image::{DynamicImage, GenericImageView, Rgba, ImageBuffer};
    
    #[derive(Default, Serialize, Deserialize)]
    struct SettingsData {
        pixel_size: u32,
        // 你可擴充更多參數,例如選擇調色盤、色彩數量等等
    }
    
    struct Win95PixelApp {
        pixel_size: u32,
        pixel_size_slider_state: iced::slider::State,
        load_image_button: button::State,
        convert_button: button::State,
        save_settings_button: button::State,
        load_settings_button: button::State,
        image_path: Option<PathBuf>,
        loaded_image: Option<DynamicImage>,
        processed_image_handle: Option<Handle>,
        settings: SettingsData,
        message: Option<String>,
    }
    
    #[derive(Debug, Clone)]
    enum Message {
        PixelSizeChanged(u32),
        LoadImage,
        ImageLoaded(Option<PathBuf>),
        ConvertImage,
        SaveSettings,
        LoadSettings,
        SettingsSaved(Result<(), String>),
        SettingsLoaded(Result<SettingsData, String>),
    }
    
    impl Application for Win95PixelApp {
        type Executor = executor::Default;
        type Message = Message;
        type Flags = ();
    
        fn new(_flags: ()) -> (Self, Command<Message>) {
            (
                Win95PixelApp {
                    pixel_size: 8,
                    pixel_size_slider_state: iced::slider::State::new(),
                    load_image_button: button::State::new(),
                    convert_button: button::State::new(),
                    save_settings_button: button::State::new(),
                    load_settings_button: button::State::new(),
                    image_path: None,
                    loaded_image: None,
                    processed_image_handle: None,
                    settings: SettingsData { pixel_size: 8 },
                    message: None,
                },
                Command::none(),
            )
        }
    
        fn title(&self) -> String {
            "Windows 95 點陣風格轉換器".into()
        }
    
        fn update(&mut self, message: Message, _clipboard: &mut Clipboard) -> Command<Message> {
            match message {
                Message::PixelSizeChanged(value) => {
                    self.pixel_size = value.max(1);
                    self.settings.pixel_size = self.pixel_size;
                }
                Message::LoadImage => {
                    // 打開系統檔案對話框
                    if let Some(path) = FileDialog::new()
                        .add_filter("Image", &["png", "jpg", "bmp"])
                        .pick_file()
                    {
                        self.image_path = Some(path.clone());
                        return Command::perform(async move { Some(path) }, Message::ImageLoaded);
                    }
                }
                Message::ImageLoaded(maybe_path) => {
                    if let Some(path) = maybe_path {
                        match image::open(&path) {
                            Ok(img) => {
                                self.loaded_image = Some(img);
                                self.message = Some(format!("已載入圖片: {:?}", path));
                                self.processed_image_handle = None; // 需重新轉換
                            }
                            Err(e) => {
                                self.message = Some(format!("無法載入圖片: {}", e));
                            }
                        }
                    }
                }
                Message::ConvertImage => {
                    if let Some(ref img) = self.loaded_image {
                        // 簡單同步轉換,實作和之前類似
                        let pixelated = pixelate_and_quantize(img, self.pixel_size);
                        // 將 image::DynamicImage 轉 iced Image Handle
                        let handle = image_to_handle(&pixelated);
                        self.processed_image_handle = Some(handle);
                        self.message = Some("轉換完成".into());
                        // 你可以另外加入儲存檔案按鈕
                    } else {
                        self.message = Some("請先載入圖片".into());
                    }
                }
                Message::SaveSettings => {
                    // 序列化 self.settings 寫入檔案
                    let s = self.settings.clone();
                    return Command::perform(async move {
                        match std::fs::write("win95_settings.json", serde_json::to_string_pretty(&s).unwrap()) {
                            Ok(_) => Ok(()),
                            Err(e) => Err(e.to_string()),
                        }
                    }, Message::SettingsSaved);
                }
                Message::SettingsSaved(result) => {
                    match result {
                        Ok(_) => self.message = Some("設定已儲存".into()),
                        Err(e) => self.message = Some(format!("儲存失敗: {}", e)),
                    }
                }
                Message::LoadSettings => {
                    return Command::perform(async move {
                        let content = std::fs::read_to_string("win95_settings.json").map_err(|e| e.to_string())?;
                        let data: SettingsData = serde_json::from_str(&content).map_err(|e| e.to_string())?;
                        Ok(data)
                    }, Message::SettingsLoaded);
                }
                Message::SettingsLoaded(result) => {
                    match result {
                        Ok(s) => {
                            self.settings = s.clone();
                            self.pixel_size = s.pixel_size;
                            self.message = Some("設定已讀取".into());
                        }
                        Err(e) => {
                            self.message = Some(format!("讀取失敗: {}", e));
                        }
                    }
                }
            }
            Command::none()
        }
    
        fn view(&mut self) -> Element<Message> {
            let sliders = Column::new()
                .spacing(10)
                .push(Text::new(format!("Pixel Size: {}", self.pixel_size)))
                .push(
                    Slider::new(
                        &mut self.pixel_size_slider_state,
                        1..=32,
                        self.pixel_size,
                        Message::PixelSizeChanged,
                    )
                    .step(1),
                );
    
            let buttons = Row::new()
                .spacing(10)
                .push(Button::new(&mut self.load_image_button, Text::new("載入圖片")).on_press(Message::LoadImage))
                .push(Button::new(&mut self.convert_button, Text::new("轉換")).on_press(Message::ConvertImage))
                .push(Button::new(&mut self.save_settings_button, Text::new("儲存設定")).on_press(Message::SaveSettings))
                .push(Button::new(&mut self.load_settings_button, Text::new("讀取設定")).on_press(Message::LoadSettings));
    
            let image_viewer = if let Some(handle) = &self.processed_image_handle {
                Image::new(handle.clone()).width(Length::Units(256)).height(Length::Units(256)).into()
            } else {
                Text::new("尚無轉換圖片").into()
            };
    
            let message_text = if let Some(m) = &self.message {
                Text::new(m).color(Color::from_rgb8(255, 0, 0))
            } else {
                Text::new("")
            };
    
            let content = Column::new()
                .padding(20)
                .spacing(15)
                .push(sliders)
                .push(buttons)
                .push(image_viewer)
                .push(message_text);
    
            Container::new(content)
                .width(Length::Fill)
                .height(Length::Fill)
                .center_x()
                .center_y()
                .into()
        }
    }
    
    /// 處理pixelate+quantize邏輯 (簡化示範,僅黑白)
    fn pixelate_and_quantize(img: &DynamicImage, pixel_size: u32) -> DynamicImage {
        let (width, height) = img.dimensions();
        let small_width = width / pixel_size.max(1);
        let small_height = height / pixel_size.max(1);
        let small_img = img.resize_exact(small_width, small_height, image::imageops::FilterType::Nearest);
    
        // Windows 95 常見的16色調色盤(簡化版)
        let palette = [
            Rgba([0, 0, 0, 255]),
            Rgba([255, 255, 255, 255]),
            Rgba([128, 128, 128, 255]),
            Rgba([192, 192, 192, 255]),
        ];
    
        fn nearest(pixel: Rgba<u8>, pal: &[Rgba<u8>]) -> Rgba<u8> {
            pal.iter()
                .min_by_key(|c| {
                    let dr = c[0] as i32 - pixel[0] as i32;
                    let dg = c[1] as i32 - pixel[1] as i32;
                    let db = c[2] as i32 - pixel[2] as i32;
                    dr * dr + dg * dg + db * db
                })
                .copied()
                .unwrap_or(pixel)
        }
    
        let mut quantized = ImageBuffer::new(small_width, small_height);
    
        for (x, y, p) in small_img.pixels() {
            let q = nearest(p, &palette);
            quantized.put_pixel(x, y, q);
        }
    
        let upscaled = image::imageops::resize(
            &quantized,
            width,
            height,
            image::imageops::FilterType::Nearest,
        );
    
        DynamicImage::ImageRgba8(upscaled)
    }
    
    /// 將image::DynamicImage轉iced支援的Image Handle
    fn image_to_handle(img: &DynamicImage) -> Handle {
        let bytes = img.to_rgba8().into_raw();
        let width = img.width();
        let height = img.height();
        Handle::from_pixels(width, height, bytes)
    }
    
    fn main() {
        Win95PixelApp::run(Settings::default());
    }
    

    使用說明

    • 按「載入圖片」彈出系統檔案選擇器,選擇圖片
    • 拖動 Pixel Size slider 調整像素大小
    • 點「轉換」執行 pixelate 和調色盤限制效果,並顯示結果預覽
    • 按「儲存設定」會把目前設定保存到 win95_settings.json
    • 按「讀取設定」取回存檔並套用

    延伸說明

    • 你可以把調色盤定義擴充成可選字串、顏色列表等 UI 控制
    • 加入更多參數調整,例如選擇調色盤種類、儲存轉換後圖片按鈕
    • 圖片太大時可能卡頓,可以用異步 Task 加速或做更完整例外處理

    如果你有興趣我也能幫你一步一步寫完整 app 範例或幫助你整合更複雜量化演算法邏輯!

  5. User

    error[E0433]: failed to resolve: could not find slider in iced --> src\main.rs:20:36 | 20 | pixel_size_slider_state: iced::slider::State, | ^^^^^^ could not find slider in iced | help: consider importing one of these modules | 1 + use conrod_core::widget::slider; | 1 + use iced::widget::slider; | help: if you import slider, refer to it directly | 20 - pixel_size_slider_state: iced::slider::State, 20 + pixel_size_slider_state: slider::State, |

    error[E0433]: failed to resolve: could not find slider in iced --> src\main.rs:53:48 | 53 | pixel_size_slider_state: iced::slider::State::new(), | ^^^^^^ could not find slider in iced
    | help: consider importing one of these structs | 1 + use conrod_core::input::State; | 1 + use conrod_core::scroll::State; | 1 + use conrod_core::widget::State; | 1 + use conrod_core::widget::bordered_rectangle::State; | and 37 other candidates help: if you import State, refer to it directly | 53 - pixel_size_slider_state: iced::slider::State::new(), 53 + pixel_size_slider_state: State::new(), |

    error[E0050]: method update has 3 parameters but the declaration in trait iced::Application::update has 2 --> src\main.rs:72:15 | 72 | fn update(&mut self, message: Message, _clipboard: &mut Clipboard) -> Command {
    | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected 2 parameters, found 3 | = note: update from trait: fn(&mut Self, <Self as iced::Application>::Message) -> iced::Command<<Self as iced::Application>::Message>

    error[E0046]: not all trait items implemented, missing: Theme --> src\main.rs:44:1 | 44 | impl Application for Win95PixelApp { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing Theme in implementation | = help: implement the missing item: type Theme = /* Type */;

    error[E0277]: SettingsData doesn't implement Debug --> src\main.rs:41:20 | 32 | #[derive(Debug, Clone)] | ----- in this derive macro expansion ... 41 | SettingsLoaded(Result<SettingsData, String>), | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ SettingsData cannot be formatted using {:?} | = help: the trait Debug is not implemented for SettingsData = note: add #[derive(Debug)] to SettingsData or manually impl Debug for SettingsData
    = help: the trait Debug is implemented for Result<T, E> help: consider annotating SettingsData with #[derive(Debug)] | 13 + #[derive(Debug)] 14 | struct SettingsData { |

    error[E0277]: the trait bound SettingsData: Clone is not satisfied --> src\main.rs:41:20 | 32 | #[derive(Debug, Clone)] | ----- in this derive macro expansion ... 41 | SettingsLoaded(Result<SettingsData, String>), | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait Clone is not implemented for SettingsData | = note: required for Result<SettingsData, std::string::String> to implement Clone help: consider annotating SettingsData with #[derive(Clone)] | 13 + #[derive(Clone)] 14 | struct SettingsData { |

    error[E0599]: no method named clone found for struct SettingsData in the current scope --> src\main.rs:117:39 | 13 | struct SettingsData { | ------------------- method clone not found for this struct ... 117 | let s = self.settings.clone(); | ^^^^^ method not found in SettingsData | = help: items from traits can only be used if the trait is implemented and in scope = note: the following trait defines an item clone, perhaps you need to implement it: candidate #1: Clone

    error[E0599]: no method named clone found for struct SettingsData in the current scope --> src\main.rs:141:43 | 13 | struct SettingsData { | ------------------- method clone not found for this struct ... 141 | self.settings = s.clone(); | ^^^^^ method not found in SettingsData | = help: items from traits can only be used if the trait is implemented and in scope = note: the following trait defines an item clone, perhaps you need to implement it: candidate #1: Clone

    error[E0599]: no variant or associated item named Units found for enum Length in the current scope --> src\main.rs:176:54 | 176 | ...).width(Length::Units(256)).height(Length::Units(256)).into() | ^^^^^ variant or associated item not found in Length

    error[E0599]: no variant or associated item named Units found for enum Length in the current scope --> src\main.rs:176:81 | 176 | ....height(Length::Units(256)).into() | ^^^^^ variant or associated item not found in Length

    Some errors have detailed explanations: E0046, E0050, E0277, E0432, E0433, E0599. For more information about an error, try rustc --explain E0046. error: could not compile my_project (bin "my_project") due to 13 previous errors

  6. Assistant

    你這問題主要是因為 iced 套件版本差異造成 API 變動與改版的問題。
    你的錯誤訊息像是新版 iced 改了結構與使用方式,導致舊程式碼找不到 slider、Length::Units,Application::update 函數簽名也變了。


    解決方向與說明

    1. iced 版本

    現階段 iced 官方穩定版本是 0.9,不過近期已釋出 0.10 甚至更高版本,API 改動大。
    你要先確認你 Cargo.toml 是指定哪個版本,原本範例用的是 0.9,新版用法不一樣。


    2. fix slider 及 UI 元件 import

    新版 iced 是把 widget 都放到子模組 iced::widget,狀況類似你錯誤訊息的建議:

    use iced::widget::{Slider, button, Button, Column, Row, Text, TextInput, Image};
    use iced::{Length, Color};
    

    這樣先直接 import 所有需要的 widget。


    3. slider::State 已不存在

    新版本 iced(0.10以上)已經不要求維護獨立 State,由 Slider 直接管理,所以不用定義 pixel_size_slider_state。

    你的 struct 定義中 pixel_size_slider_state: iced::slider::State 移除即可。


    4. Length::Units 改為 Length::Length

    新版 iced 有三種:

    • Length::Shrink
    • Length::Fill
    • Length::Units(u16) (0.10版改成 Length::Length(u16))

    如果你用 0.9 是 Length::Units(u16), 0.10 版改成:

    Length::Length(256)
    

    5. Application trait 更新

    Signature 改了:

    update(&mut self, message: Self::Message) -> Command<Self::Message>

    不再有 Clipboard 參數,請移除。


    6. Debug、Clone traits

    SettingsData 沒有添加需要的 #[derive(Debug, Clone)],記得補上:

    #[derive(Debug, Clone, Serialize, Deserialize)]
    struct SettingsData {
        pixel_size: u32,
    }
    

    針對你的編譯錯誤,修正版範例大致如下:

    use iced::{
        widget::{button, Button, Column, Row, Slider, Text, Image},
        executor, Application, Command, Container, Element, Length, Settings, Color,
    };
    use iced_native::image::Handle;
    use rfd::FileDialog;
    use serde::{Deserialize, Serialize};
    use std::path::PathBuf;
    use image::{DynamicImage, GenericImageView, Rgba, ImageBuffer};
    
    #[derive(Debug, Clone, Serialize, Deserialize)]
    struct SettingsData {
        pixel_size: u32,
    }
    
    struct Win95PixelApp {
        pixel_size: u32,
        load_image_button: button::State,
        convert_button: button::State,
        save_settings_button: button::State,
        load_settings_button: button::State,
        image_path: Option<PathBuf>,
        loaded_image: Option<DynamicImage>,
        processed_image_handle: Option<Handle>,
        settings: SettingsData,
        message: Option<String>,
    }
    
    #[derive(Debug, Clone)]
    enum Message {
        PixelSizeChanged(u32),
        LoadImage,
        ImageLoaded(Option<PathBuf>),
        ConvertImage,
        SaveSettings,
        LoadSettings,
        SettingsSaved(Result<(), String>),
        SettingsLoaded(Result<SettingsData, String>),
    }
    
    impl Application for Win95PixelApp {
        type Executor = executor::Default;
        type Message = Message;
        type Theme = iced::theme::Theme; // iced 0.10 以上需要指定Theme
        type Flags = ();
    
        fn new(_flags: ()) -> (Self, Command<Message>) {
            (
                Win95PixelApp {
                    pixel_size: 8,
                    load_image_button: button::State::new(),
                    convert_button: button::State::new(),
                    save_settings_button: button::State::new(),
                    load_settings_button: button::State::new(),
                    image_path: None,
                    loaded_image: None,
                    processed_image_handle: None,
                    settings: SettingsData { pixel_size: 8 },
                    message: None,
                },
                Command::none(),
            )
        }
    
        fn title(&self) -> String {
            "Windows 95 點陣風格轉換器".into()
        }
    
        fn update(&mut self, message: Message) -> Command<Message> {
            match message {
                Message::PixelSizeChanged(value) => {
                    self.pixel_size = value.max(1);
                    self.settings.pixel_size = self.pixel_size;
                }
                Message::LoadImage => {
                    if let Some(path) = FileDialog::new()
                        .add_filter("Image", &["png", "jpg", "bmp"])
                        .pick_file()
                    {
                        self.image_path = Some(path.clone());
                        return Command::perform(async move { Some(path) }, Message::ImageLoaded);
                    }
                }
                Message::ImageLoaded(maybe_path) => {
                    if let Some(path) = maybe_path {
                        match image::open(&path) {
                            Ok(img) => {
                                self.loaded_image = Some(img);
                                self.message = Some(format!("已載入圖片: {:?}", path));
                                self.processed_image_handle = None;
                            }
                            Err(e) => {
                                self.message = Some(format!("無法載入圖片: {}", e));
                            }
                        }
                    }
                }
                Message::ConvertImage => {
                    if let Some(ref img) = self.loaded_image {
                        let pixelated = pixelate_and_quantize(img, self.pixel_size);
                        let handle = image_to_handle(&pixelated);
                        self.processed_image_handle = Some(handle);
                        self.message = Some("轉換完成".into());
                    } else {
                        self.message = Some("請先載入圖片".into());
                    }
                }
                Message::SaveSettings => {
                    let s = self.settings.clone();
                    return Command::perform(async move {
                        match std::fs::write("win95_settings.json", serde_json::to_string_pretty(&s).unwrap()) {
                            Ok(_) => Ok(()),
                            Err(e) => Err(e.to_string()),
                        }
                    }, Message::SettingsSaved);
                }
                Message::SettingsSaved(result) => {
                    match result {
                        Ok(_) => self.message = Some("設定已儲存".into()),
                        Err(e) => self.message = Some(format!("儲存失敗: {}", e)),
                    }
                }
                Message::LoadSettings => {
                    return Command::perform(async move {
                        let content = std::fs::read_to_string("win95_settings.json").map_err(|e| e.to_string())?;
                        let data: SettingsData = serde_json::from_str(&content).map_err(|e| e.to_string())?;
                        Ok(data)
                    }, Message::SettingsLoaded);
                }
                Message::SettingsLoaded(result) => {
                    match result {
                        Ok(s) => {
                            self.settings = s.clone();
                            self.pixel_size = s.pixel_size;
                            self.message = Some("設定已讀取".into());
                        }
                        Err(e) => {
                            self.message = Some(format!("讀取失敗: {}", e));
                        }
                    }
                }
            }
            Command::none()
        }
    
        fn view(&mut self) -> Element<Message> {
            let sliders = Column::new()
                .spacing(10)
                .push(Text::new(format!("Pixel Size: {}", self.pixel_size)))
                .push(
                    Slider::new(1..=32, self.pixel_size, Message::PixelSizeChanged).step(1),
                );
    
            let buttons = Row::new()
                .spacing(10)
                .push(Button::new(&mut self.load_image_button, Text::new("載入圖片")).on_press(Message::LoadImage))
                .push(Button::new(&mut self.convert_button, Text::new("轉換")).on_press(Message::ConvertImage))
                .push(Button::new(&mut self.save_settings_button, Text::new("儲存設定")).on_press(Message::SaveSettings))
                .push(Button::new(&mut self.load_settings_button, Text::new("讀取設定")).on_press(Message::LoadSettings));
    
            let image_viewer = if let Some(handle) = &self.processed_image_handle {
                Image::new(handle.clone()).width(Length::Length(256)).height(Length::Length(256)).into()
            } else {
                Text::new("尚無轉換圖片").into()
            };
    
            let message_text = if let Some(m) = &self.message {
                Text::new(m).color(Color::from_rgb8(255, 0, 0))
            } else {
                Text::new("")
            };
    
            let content = Column::new()
                .padding(20)
                .spacing(15)
                .push(sliders)
                .push(buttons)
                .push(image_viewer)
                .push(message_text);
    
            Container::new(content)
                .width(Length::Fill)
                .height(Length::Fill)
                .center_x()
                .center_y()
                .into()
        }
    }
    
    fn pixelate_and_quantize(img: &DynamicImage, pixel_size: u32) -> DynamicImage {
        let (width, height) = img.dimensions();
        let small_width = width / pixel_size.max(1);
        let small_height = height / pixel_size.max(1);
        let small_img = img.resize_exact(small_width, small_height, image::imageops::FilterType::Nearest);
    
        let palette = [
            Rgba([0, 0, 0, 255]),
            Rgba([255, 255, 255, 255]),
            Rgba([128, 128, 128, 255]),
            Rgba([192, 192, 192, 255]),
        ];
    
        fn nearest(pixel: Rgba<u8>, pal: &[Rgba<u8>]) -> Rgba<u8> {
            pal.iter()
                .min_by_key(|c| {
                    let dr = c[0] as i32 - pixel[0] as i32;
                    let dg = c[1] as i32 - pixel[1] as i32;
                    let db = c[2] as i32 - pixel[2] as i32;
                    dr * dr + dg * dg + db * db
                })
                .copied()
                .unwrap_or(pixel)
        }
    
        let mut quantized = ImageBuffer::new(small_width, small_height);
    
        for (x, y, p) in small_img.pixels() {
            let q = nearest(p, &palette);
            quantized.put_pixel(x, y, q);
        }
    
        let upscaled = image::imageops::resize(
            &quantized,
            width,
            height,
            image::imageops::FilterType::Nearest,
        );
    
        DynamicImage::ImageRgba8(upscaled)
    }
    
    fn image_to_handle(img: &DynamicImage) -> Handle {
        let bytes = img.to_rgba8().into_raw();
        let width = img.width();
        let height = img.height();
        Handle::from_pixels(width, height, bytes)
    }
    
    fn main() {
        Win95PixelApp::run(Settings::default());
    }
    

    總結:

    • 確認 iced 版本 (cargo tree | grep iced)
    • 用合適版本的 API,去官方文檔或 iced crate 查新版用法
    • 移除所有 slider::State,因為它已被拿掉了(除非你特別用老版本)
    • Length::Units 改為 Length::Length 或參考版型文件
    • Application::update 只有兩參數(self & message)
    • 結構體加上 #[derive(Debug, Clone)] 以符合 trait bound

    如果你想快速拿到可跑的版本,Cargo.toml:

    [dependencies]
    image = "0.24"
    palette = "0.6"
    iced = "0.9"  # 與我最初範例對應版本,API相容
    serde = {version = "1.0", features=["derive"]}
    serde_json = "1.0"
    rfd = "0.11"
    

    或

    換成新版需調整上述 API 使用方式。


    若需要,我可以幫你直接整理一份最新 iced 0.10+ 的對應範例。
    你需要幫忙請說!

  7. User

    完整程式碼

  8. Assistant

    以下提供一份使用 iced 0.10(目前較新版本)的完整 Rust GUI 程式碼範例,具備:

    • 調整 pixel size 的 slider
    • 讀取圖片(用 rfd 系統檔案選擇)
    • 轉換為 Win95 點陣圖風格(簡單 pixelate+16色量化)
    • 顯示轉換後結果
    • 儲存與讀取設定(JSON)
    • 簡單訊息顯示

    Cargo.toml

    [package]
    name = "win95_pixelator"
    version = "0.1.0"
    edition = "2021"
    
    [dependencies]
    iced = { version = "0.10", features = ["image", "svg"] } 
    image = "0.24"
    serde = { version = "1.0", features = ["derive"] }
    serde_json = "1.0"
    rfd = "0.11"
    

    src/main.rs

    use iced::widget::{button, Button, Column, Row, Slider, Text, Image, Scrollable, scrollable};
    use iced::{executor, Application, Clipboard, Command, Container, Element, Length, Settings, Theme, Color};
    use iced::image::Handle;
    
    use rfd::FileDialog;
    
    use serde::{Deserialize, Serialize};
    
    use std::path::PathBuf;
    
    use image::{DynamicImage, GenericImageView, Rgba, ImageBuffer};
    
    #[derive(Debug, Clone, Serialize, Deserialize)]
    struct SettingsData {
        pixel_size: u32,
    }
    
    struct Win95PixelApp {
        pixel_size: u32,
        loaded_image: Option<DynamicImage>,
        processed_image_handle: Option<Handle>,
        message: Option<String>,
        settings: SettingsData,
    
        load_image_btn: button::State,
        convert_btn: button::State,
        save_settings_btn: button::State,
        load_settings_btn: button::State,
        scroll: scrollable::State,
    }
    
    #[derive(Debug, Clone)]
    enum Message {
        PixelSizeChanged(u32),
        LoadImage,
        ImageLoaded(Option<PathBuf>),
        ConvertImage,
        SaveSettings,
        LoadSettings,
        SettingsSaved(Result<(), String>),
        SettingsLoaded(Result<SettingsData, String>),
    }
    
    impl Application for Win95PixelApp {
        type Message = Message;
        type Executor = executor::Default;
        type Theme = Theme;
        type Flags = ();
    
        fn new(_flags: ()) -> (Self, Command<Message>) {
            (
                Win95PixelApp {
                    pixel_size: 8,
                    loaded_image: None,
                    processed_image_handle: None,
                    message: None,
                    settings: SettingsData { pixel_size: 8 },
                    load_image_btn: button::State::new(),
                    convert_btn: button::State::new(),
                    save_settings_btn: button::State::new(),
                    load_settings_btn: button::State::new(),
                    scroll: scrollable::State::new(),
                },
                Command::none(),
            )
        }
    
        fn title(&self) -> String {
            String::from("Windows 95 Pixelator")
        }
    
        fn update(&mut self, message: Message, _clipboard: &mut Clipboard) -> Command<Message> {
            match message {
                Message::PixelSizeChanged(val) => {
                    self.pixel_size = val.max(1);
                    self.settings.pixel_size = self.pixel_size;
                }
                Message::LoadImage => {
                    if let Some(path) = FileDialog::new()
                        .add_filter("圖片", &["png", "jpg", "bmp", "jpeg"])
                        .pick_file()
                    {
                        return Command::perform(async move { Some(path) }, Message::ImageLoaded);
                    }
                }
                Message::ImageLoaded(opt_path) => {
                    if let Some(path) = opt_path {
                        match image::open(&path) {
                            Ok(img) => {
                                self.loaded_image = Some(img);
                                self.message = Some(format!("成功載入圖片:{}", path.display()));
                                self.processed_image_handle = None;
                            }
                            Err(e) => self.message = Some(format!("載入圖片失敗: {}", e)),
                        }
                    }
                }
                Message::ConvertImage => {
                    if let Some(img) = &self.loaded_image {
                        let result_img = pixelate_and_quantize(img, self.pixel_size);
                        self.processed_image_handle = Some(image_to_handle(&result_img));
                        self.message = Some("轉換完成".into());
                    } else {
                        self.message = Some("請先載入圖片".into());
                    }
                }
                Message::SaveSettings => {
                    let s = self.settings.clone();
                    return Command::perform(
                        async move {
                            let json = serde_json::to_string_pretty(&s).map_err(|e| e.to_string())?;
                            std::fs::write("win95_settings.json", json).map_err(|e| e.to_string())
                        },
                        Message::SettingsSaved,
                    );
                }
                Message::SettingsSaved(res) => match res {
                    Ok(()) => self.message = Some("設定已儲存".into()),
                    Err(e) => self.message = Some(format!("儲存失敗: {}", e)),
                },
                Message::LoadSettings => {
                    return Command::perform(
                        async move {
                            let content = std::fs::read_to_string("win95_settings.json").map_err(|e| e.to_string())?;
                            let s: SettingsData = serde_json::from_str(&content).map_err(|e| e.to_string())?;
                            Ok(s)
                        },
                        Message::SettingsLoaded,
                    );
                }
                Message::SettingsLoaded(res) => match res {
                    Ok(s) => {
                        self.settings = s.clone();
                        self.pixel_size = s.pixel_size;
                        self.message = Some("設定已讀取".into());
                    }
                    Err(e) => self.message = Some(format!("讀取失敗: {}", e)),
                },
            }
            Command::none()
        }
    
        fn view(&mut self) -> Element<Message> {
            let slider = Slider::new(1..=32, self.pixel_size, Message::PixelSizeChanged).step(1);
    
            let controls = Row::new()
                .spacing(10)
                .push(
                    Button::new(&mut self.load_image_btn, Text::new("載入圖片"))
                        .on_press(Message::LoadImage),
                )
                .push(
                    Button::new(&mut self.convert_btn, Text::new("轉換"))
                        .on_press(Message::ConvertImage),
                )
                .push(
                    Button::new(&mut self.save_settings_btn, Text::new("儲存設定"))
                        .on_press(Message::SaveSettings),
                )
                .push(
                    Button::new(&mut self.load_settings_btn, Text::new("讀取設定"))
                        .on_press(Message::LoadSettings),
                );
    
            let message_text = if let Some(msg) = &self.message {
                Text::new(msg).color(Color::from_rgb8(255, 0, 0))
            } else {
                Text::new("")
            };
    
            let image_view = if let Some(handle) = &self.processed_image_handle {
                Image::new(handle.clone())
                    .width(Length::Units(256))
                    .height(Length::Units(256))
                    .into()
            } else {
                Text::new("尚無轉換圖片").into()
            };
    
            let content = Column::new()
                .spacing(15)
                .padding(20)
                .push(Text::new(format!("Pixel Size: {}", self.pixel_size)))
                .push(slider)
                .push(controls)
                .push(message_text)
                .push(image_view);
    
            Scrollable::new(&mut self.scroll)
                .push(content)
                .into()
        }
    }
    
    /// Pixelate並量化(簡單16色Windows95調色盤)
    fn pixelate_and_quantize(img: &DynamicImage, pixel_size: u32) -> DynamicImage {
        let (width, height) = img.dimensions();
        let pixel_size = pixel_size.max(1);
    
        let sw = width / pixel_size;
        let sh = height / pixel_size;
    
        let small = img.resize_exact(sw, sh, image::imageops::FilterType::Nearest);
    
        // Windows 95 16色常見色
        let palette: [Rgba<u8>; 16] = [
            Rgba([0, 0, 0, 255]),
            Rgba([0, 0, 128, 255]),
            Rgba([0, 128, 0, 255]),
            Rgba([0, 128, 128, 255]),
            Rgba([128, 0, 0, 255]),
            Rgba([128, 0, 128, 255]),
            Rgba([128, 128, 0, 255]),
            Rgba([192, 192, 192, 255]),
            Rgba([128, 128, 128, 255]),
            Rgba([0, 0, 255, 255]),
            Rgba([0, 255, 0, 255]),
            Rgba([0, 255, 255, 255]),
            Rgba([255, 0, 0, 255]),
            Rgba([255, 0, 255, 255]),
            Rgba([255, 255, 0, 255]),
            Rgba([255, 255, 255, 255]),
        ];
    
        fn nearest_color(px: Rgba<u8>, palette: &[Rgba<u8>]) -> Rgba<u8> {
            palette
                .iter()
                .min_by_key(|c| {
                    let dr = (*c)[0] as i32 - px[0] as i32;
                    let dg = (*c)[1] as i32 - px[1] as i32;
                    let db = (*c)[2] as i32 - px[2] as i32;
                    dr * dr + dg * dg + db * db
                })
                .copied()
                .unwrap_or(px)
        }
    
        let mut quant = ImageBuffer::new(sw, sh);
    
        for (x, y, px) in small.pixels() {
            let q = nearest_color(px, &palette);
            quant.put_pixel(x, y, q);
        }
    
        let upscaled = image::imageops::resize(&quant, width, height, image::imageops::FilterType::Nearest);
    
        DynamicImage::ImageRgba8(upscaled)
    }
    
    fn image_to_handle(img: &DynamicImage) -> Handle {
        let rgba = img.to_rgba8();
        Handle::from_pixels(img.width(), img.height(), rgba.into_raw())
    }
    
    fn main() -> iced::Result {
        Win95PixelApp::run(Settings {
            window: iced::window::Settings {
                size: (600, 700),
                ..Default::default()
            },
            ..Settings::default()
        })
    }
    

    使用說明

    1. cargo run 啟動視窗
    2. 用「載入圖片」選取要轉換的圖檔(支援 png,jpg,bmp 等)
    3. 調整右上方 Pixel Size slider,決定像素塊大小
    4. 點「轉換」產生 Win95風格 點陣效果(會顯示在畫面下方)
    5. 可用「儲存設定」保存 pixel size 等參數,下次用「讀取設定」載回

    注意

    • 這範例以 iced 0.10.x API 為基礎,其他版本(如0.9)需要調整相應符號
    • 調色盤是16色 Win95常見色,你可以自己擴充優化演算法
    • 示範為同步操作,圖片太大轉換慢會卡UI,可用 async Task 優化

    如果有需要我可以幫忙做:

    • 進階調色盤客製UI
    • 儲存轉換後圖片按鈕
    • 公開可執行檔指引

    歡迎告訴我!

  9. User

    winit = "0.28"一個乾淨的winit

  10. Assistant

    你想要一個「乾淨的」winit = "0.28" 使用範例,也就是只用 winit(不含圖形繪製引擎或GUI套件),單純創建一個視窗、處理事件的 Rust 程式碼。下面是符合你要求的最基本範例:


    Cargo.toml

    [package]
    name = "winit_minimal"
    version = "0.1.0"
    edition = "2021"
    
    [dependencies]
    winit = "0.28"
    

    src/main.rs

    use winit::{
        event::{Event, WindowEvent, KeyboardInput, ElementState, VirtualKeyCode},
        event_loop::{ControlFlow, EventLoop},
        window::WindowBuilder,
    };
    
    fn main() {
        // 建立事件循環
        let event_loop = EventLoop::new();
    
        // 建立視窗
        let window = WindowBuilder::new()
            .with_title("Minimal winit Example")
            .with_inner_size(winit::dpi::LogicalSize::new(800.0, 600.0))
            .build(&event_loop)
            .unwrap();
    
        // 啟動事件循環
        event_loop.run(move |event, _, control_flow| {
            *control_flow = ControlFlow::Wait;
    
            match event {
                // 處理視窗事件
                Event::WindowEvent { event, .. } => match event {
                    WindowEvent::CloseRequested => {
                        // 視窗關閉事件,結束程式
                        *control_flow = ControlFlow::Exit;
                    }
                    WindowEvent::KeyboardInput { input, .. } => {
                        // 按鍵輸入事件
                        if let KeyboardInput {
                            state: ElementState::Pressed,
                            virtual_keycode: Some(VirtualKeyCode::Escape),
                            ..
                        } = input
                        {
                            // 按 ESC 離開程式
                            *control_flow = ControlFlow::Exit;
                        }
                    }
                    _ => {}
                },
                Event::MainEventsCleared => {
                    // 這邊是每 frame 的邏輯
                    // 如果要畫畫或更新狀態,可放這裡
                }
                _ => {}
            }
        });
    }
    

    程式說明

    • 建立一個 800x600 的視窗,標題為 "Minimal winit Example"
    • 事件循環裡監聽視窗關閉事件(點x),或按 ESC 鍵都會關閉程式
    • 其餘事件會忽略
    • 使用 ControlFlow::Wait 讓事件循環對 CPU 不會一直燒

    編譯執行

    cargo run
    

    你會看到一個空白視窗顯示,可以關閉或按 ESC 離開。


    這就是一個最基本、乾淨、只用 winit 且符合你指定版本的範例示範。
    如果你需要跟其他圖形渲染(OpenGL、wgpu)整合,也可以再告訴我!

  11. User

    winit可以控制跟遊戲一樣的放大的全螢幕嗎

  12. Assistant

    winit 本身是用來管理視窗和事件的,它可以控制視窗的模式,但真正「全螢幕放大且保留比例(像遊戲的全螢幕縮放)」的行為,通常需要你自己搭配繪圖(如 OpenGL、wgpu)來處理畫面縮放與渲染。

    不過,winit 提供了全螢幕切換、視窗大小控制、以及 DPI 比例查詢等功能,你可以用這些來達成類似遊戲「全螢幕且放大畫面」的行為。


    重點:winit 支援切換全螢幕、設定視窗大小與顯示模式

    winit 透過 Window::set_fullscreen 可以切換全螢幕模式。

    • None → 視窗模式
    • Some(Fullscreen::Borderless(Some(MonitorHandle))) → 無邊框全螢幕(覆蓋整個螢幕)
    • Some(Fullscreen::Exclusive(VideoMode)) → 專屬全螢幕(切換到指定的解析度)

    範例示範:按下 F11 切換「無邊框全螢幕」

    use winit::{
        event::{Event, WindowEvent, KeyboardInput, ElementState, VirtualKeyCode},
        event_loop::{ControlFlow, EventLoop},
        window::{WindowBuilder, Fullscreen},
    };
    
    fn main() {
        let event_loop = EventLoop::new();
    
        let window = WindowBuilder::new()
            .with_title("Fullscreen Toggle Example")
            .with_inner_size(winit::dpi::LogicalSize::new(800.0, 600.0))
            .build(&event_loop)
            .unwrap();
    
        let mut fullscreen = false;
    
        event_loop.run(move |event, _, control_flow| {
            *control_flow = ControlFlow::Wait;
    
            match event {
                Event::WindowEvent { event, .. } => match event {
                    WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit,
    
                    WindowEvent::KeyboardInput { input, .. } => {
                        if let KeyboardInput {
                            state: ElementState::Pressed,
                            virtual_keycode: Some(key),
                            ..
                        } = input
                        {
                            match key {
                                VirtualKeyCode::Escape => *control_flow = ControlFlow::Exit,
    
                                VirtualKeyCode::F11 => {
                                    fullscreen = !fullscreen;
                                    if fullscreen {
                                        window.set_fullscreen(Some(Fullscreen::Borderless(None)));
                                    } else {
                                        window.set_fullscreen(None);
                                    }
                                }
                                _ => {}
                            }
                        }
                    }
                    _ => {}
                },
                _ => {}
            }
        });
    }
    

    按 F11 可以在無邊框全螢幕和視窗模式,ESC 離開。


    放大畫面、保持比例

    winit 無法直接「放大」你的內容或畫面,這個部分要你用 OpenGL / Vulkan / wgpu 等繪圖 API 來自己控制。
    常見做法是:

    1. 在切換全螢幕或視窗大小時,算出螢幕(或視窗)大小與你的「設計解析度」比例
    2. 繪圖時先把繪製目標按比例縮放(viewport、projection 或 shader)
    3. 可能用 letterboxing(黑邊)避免失真

    總結

    • winit 可以讓你切換無邊框全螢幕、專屬全螢幕,控制視窗顯示模式
    • 畫面「放大與保持比例」則要靠你搭配繪圖程式碼實作
    • 遊戲開發中,winit 常當作事件與視窗核心,搭配 SDL2、wgpu、glow、gfx、gfx-hal 等渲染層

    如果你想,我可以幫你示範一個 winit + wgpu,能正確全螢幕切換且畫面縮放保持比例的範例。
    或者希望示範 OpenGL 的狀況也可以。


    需要範例嗎?
    請告訴我你用哪個渲染 API (wgpu?OpenGL?Vulkan?) 我幫你示範!

  13. User

    use piston::event_loop; use winit::{ event::{Event,WindowEvent,KeyboardInput,ElementState,VirtualKeyCode}, event_loop::{ControlFlow,EventLoop}, window::WindowBuilder, }

    fn main(){ let event_loop=EventLoop::new(); let window22=WindowBuilder::new() .with_title("範例") .with_inner_size(winit::dpi::LogicalSize::new(800.0,600.0)) .build(&event_loop) .unwrap();

        event_loop.run(move|event,_,control_flow|{
            *control_flow=ControlFlow::Wait;
    
    
                match event  {
    
                    Event::WindowEvent {  event,.. }=>match event {
                        WindowEvent::CloseRequested=>{
                            *control_flow=ControlFlow::Exit;
                        }
                        WindowEvent::KeyboardInput { input, .. }=>{
                            if let KeyboardInput { state:ElementState::Pressed, virtual_keycode:Some(VisturalKeycode::Escape),.. }=input
                        {
                            *control_flow=ControlFlow::Exit;
                        }
                        
    
    
                    }
    
    
                    _=>{}
                },
                Event::MainEventsCleared=>{
                    _=>{}
                }
        });
         
    

    } 請找錯誤

  14. Assistant

    你貼的程式碼有幾個語法錯誤和拼字錯誤,還有結尾括號和 match 寫法錯誤,下面幫你列出錯誤點與修正:


    你原本 code 的問題

    1. use piston::event_loop;
      你程式中沒用到 piston,且它和 winit 是兩個不同生態系,如果想用 winit 不要 import piston 的東西。

    2. use winit::{ ..., } 最後一個逗號改成分號

    3. if let KeyboardInput { state:ElementState::Pressed, virtual_keycode:Some(VisturalKeycode::Escape),.. }=input

      • VisturalKeycode 拼錯,正確是 VirtualKeyCode
    4. Event::MainEventsCleared=>{ _=>{} }
      這裡 match 寫法錯誤,不應在這個分支中出現 _=>{}, Event::MainEventsCleared => {} 就好。

    5. 函式結尾,event_loop.run 的閉包內括號不匹配。你要確保 match event { ... } 括號對齊。

    6. 結尾的 } 數量不足。


    修正後的完整 code

    use winit::{
        event::{Event, WindowEvent, KeyboardInput, ElementState, VirtualKeyCode},
        event_loop::{ControlFlow, EventLoop},
        window::WindowBuilder,
    };
    
    fn main() {
        let event_loop = EventLoop::new();
        let window22 = WindowBuilder::new()
            .with_title("範例")
            .with_inner_size(winit::dpi::LogicalSize::new(800.0, 600.0))
            .build(&event_loop)
            .unwrap();
    
        event_loop.run(move |event, _, control_flow| {
            *control_flow = ControlFlow::Wait;
    
            match event {
                Event::WindowEvent { event, .. } => match event {
                    WindowEvent::CloseRequested => {
                        *control_flow = ControlFlow::Exit;
                    }
                    WindowEvent::KeyboardInput { input, .. } => {
                        if let KeyboardInput {
                            state: ElementState::Pressed,
                            virtual_keycode: Some(VirtualKeyCode::Escape),
                            ..
                        } = input
                        {
                            *control_flow = ControlFlow::Exit;
                        }
                    }
                    _ => {}
                },
                Event::MainEventsCleared => {
                    // 可在這更新狀態或 redraw
                }
                _ => {}
            }
        });
    }
    

    總結

    • 移除 piston 相關 use ,因為你程式碼只用 winit
    • 修正拼字錯誤 VirtualKeyCode
    • match 的大括號對齊並刪除錯誤的 _=>{}
    • 事件閉包參數 (_, _, _) 對應 event_loop.run 正確參數列表

    如果你需要我幫你範例加上更多功能或說明,歡迎隨時問!