【学Rust写CAD】26 图形像素获取(pixel_fetch.rs)

源码

rust 复制代码
use super::image::Image;

pub trait PixelFetch {
    fn get_pixel(bitmap: &Image,  x: i32,  y: i32) -> u32;
}

pub struct PadFetch;
impl PixelFetch for PadFetch{
    fn get_pixel(bitmap: &Image, mut x: i32, mut y: i32) -> u32 {
        if x < 0 {
            x = 0;
        }
        if x >= bitmap.width {
            x = bitmap.width - 1;
        }

        if y < 0 {
            y = 0;
        }
        if y >= bitmap.height {
            y = bitmap.height - 1;
        }

        bitmap.data[(y * bitmap.width + x) as usize]
    }
}

代码分析

这段代码定义了一个像素获取的 trait 和其实现,主要用于从图像中安全地获取像素值,同时处理越界访问的情况。以下是详细解释:

  1. 引入依赖和定义 trait
rust 复制代码
use super::image::Image;

pub trait PixelFetch {
    fn get_pixel(bitmap: &Image, x: i32, y: i32) -> u32;
}
  • use super::image::Image;: 引入父模块中的 Image 类型,表示图像数据结构。

  • PixelFetch trait: 定义了一个接口,要求实现 get_pixel 方法,用于从图像中获取指定坐标 (x, y) 的像素值(u32 类型)。

  1. 实现 PadFetch 结构体
rust 复制代码
pub struct PadFetch;
impl PixelFetch for PadFetch {
    fn get_pixel(bitmap: &Image, mut x: i32, mut y: i32) -> u32 {
        // 处理 x 越界
        if x < 0 {
            x = 0;
        }
        if x >= bitmap.width {
            x = bitmap.width - 1;
        }

        // 处理 y 越界
        if y < 0 {
            y = 0;
        }
        if y >= bitmap.height {
            y = bitmap.height - 1;
        }

        // 返回安全坐标下的像素值
        bitmap.data[(y * bitmap.width + x) as usize]
    }
}
  • PadFetch: 一个空结构体,实现了 PixelFetch trait,提供边界填充(Padding)的像素获取策略。

  • 越界处理逻辑:

    • 如果 x 或 y 为负数,将其修正为 0(图像左/上边界)。

    • 如果 x 或 y 超过图像宽度或高度,将其修正为 width - 1 或 height - 1(图像右/下边界)。

  • 像素计算: 修正后的坐标通过 y * width + x 转换为线性索引,从 bitmap.data(像素数组)中取出对应的 u32 像素值。

关键点总结

  • 用途: 安全地获取图像像素,避免因越界访问导致 panic 或内存不安全。

  • 策略: 越界时返回最近的边界像素值(类似"边缘填充"效果)。

  • 适用场景: 图像处理中需要处理边界条件的操作(如卷积滤波、缩放等)。

如果需要其他边界处理方式(如镜像、重复等),可以定义新的结构体并实现 PixelFetch trait。

相关推荐
红烧code38 分钟前
【Rust GUI开发入门】编写一个本地音乐播放器(1. 主要技术选型&架构设计)
rust·gui·slint·rodio·lofty
JordanHaidee2 小时前
【Rust GUI开发入门】编写一个本地音乐播放器(3. UI与后台线程通信)
rust
Source.Liu20 小时前
【mdBook】1 安装
笔记·rust·markdown
Vallelonga21 小时前
Rust 中的 static 和 const
开发语言·经验分享·rust
s91236010121 小时前
【rust】 pub(crate) 的用法
开发语言·后端·rust
新石器程序员1 天前
借鉴bevy实现适用于Godot-rust的状态管理
rust·游戏引擎·godot·bevy
啦工作呢1 天前
Sass:CSS 预处理器
开发语言·后端·rust
中国胖子风清扬1 天前
Rust MCP:构建智能上下文协议的未来桥梁
后端·ai·rust·ai编程·language model·ai-native·mcp
xiaguangbo2 天前
rust slint android 安卓
android·linux·rust
s9123601012 天前
[rust] temporary value dropped while borrowed
开发语言·后端·rust