You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Slint 1.1.1(Rust 1.71)中如何渲染自定义绘制图像?

Slint Image组件自定义图像展示与更新指南

一、.slint文件中集成Image组件的属性

在.slint文件里,需要给Image组件设置**source**属性,该属性接收Image类型的数据,通常绑定到Rust侧暴露的属性变量。示例代码如下:

export component MainWindow inherits Window {
    // 声明接收Rust侧图像数据的属性
    in property<Image> canvas_image;

    canvas := Image {
        // 绑定图像源到声明的属性
        source: canvas_image;
        // 可根据需求设置宽高
        width: 400px;
        height: 300px;
    }
}

二、更新画布图像的属性与Rust实现

更新图像时同样修改source绑定的属性值,Rust侧需要通过SharedPixelBuffer创建图像数据,再转换为Slint的Image类型传递给组件。

Rust示例代码

use slint::{slint, SharedPixelBuffer, Image, Rgb8Pixel};

// 导入slint组件定义
slint!{
    export component MainWindow inherits Window {
        in property<Image> canvas_image;
        canvas := Image {
            source: canvas_image;
            width: 400px;
            height: 300px;
        }
    }
}

fn main() -> Result<(), slint::PlatformError> {
    let window = MainWindow::new()?;

    // 1. 初始化自定义图像
    let mut init_buffer = SharedPixelBuffer::<Rgb8Pixel>::new(400, 300);
    // 填充红色背景示例
    for pixel in init_buffer.iter_mut() {
        *pixel = Rgb8Pixel { r: 255, g: 0, b: 0 };
    }
    let init_image = Image::from_rgb8(init_buffer);
    window.set_canvas_image(init_image);

    // 2. 模拟后续更新图像(比如延迟2秒后切换为绿色背景)
    std::thread::spawn({
        let window_clone = window.clone();
        move || {
            std::thread::sleep(std::time::Duration::from_secs(2));
            let mut update_buffer = SharedPixelBuffer::<Rgb8Pixel>::new(400, 300);
            for pixel in update_buffer.iter_mut() {
                *pixel = Rgb8Pixel { r: 0, g: 255, b: 0 };
            }
            let update_image = Image::from_rgb8(update_buffer);
            // 更新属性触发界面刷新
            window_clone.set_canvas_image(update_image);
        }
    });

    window.run()
}

关键说明

  • SharedPixelBuffer是Slint提供的线程安全像素缓冲区,适合在UI线程或其他线程中创建/修改图像数据。
  • 每次更新只需调用set_xxx方法修改绑定的属性值,Slint会自动触发Image组件的重绘。

内容的提问来源于stack exchange,提问作者Jan Diederich

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 19:35:12