【学Rust写CAD】20 平铺模式结构体(spread.rs)

这个 Spread。rs文件定义了渐变超出定义区域时的扩展方式,通常用于处理渐变在边界之外的行为。

源码

rust 复制代码
//color/spread.rs
#[derive(Debug, Clone, Copy)]
pub struct Pad;  // 空结构体,表示 Pad 模式

#[derive(Debug, Clone, Copy)]
pub struct Reflect;  // 空结构体,表示 Reflect 模式

#[derive(Debug, Clone, Copy)]
pub struct Repeat;  // 空结构体,表示 Repeat 模式

trait Spread {
    fn apply(&self, x: i32) -> i32;
}

impl Spread for Pad {
    fn apply(&self, x: i32) -> i32 {
        if x > 255 {
            255
        } else if x < 0 {
            0
        } else {
            x
        }
    }
}

impl Spread for Repeat {
    fn apply(&self, x: i32) -> i32 {
        x & 255
    }
}

impl Spread for Reflect {
    fn apply(&self, x: i32) -> i32 {
        let sign = (x << 23) >> 31;
        (x ^ sign) & 255
    }
}

代码分析

这段代码定义了几种不同的颜色值处理模式,用于处理超出标准RGB范围(0-255)的数值。

主要组成部分

  1. 模式定义
    定义了三个空结构体,分别表示不同的处理模式:
rust 复制代码
pub struct Pad;     // Pad模式
pub struct Reflect; // Reflect模式
pub struct Repeat;  // Repeat模式

这些结构体都是空结构体(零大小类型),仅用作标记类型(tag types)来实现不同的行为。

  1. Spread trait
    定义了一个trait Spread,它有一个方法apply,接受一个i32参数并返回处理后的i32值:
rust 复制代码
trait Spread {
    fn apply(&self, x: i32) -> i32;
}
  1. 不同模式的实现
Pad模式
rust 复制代码
impl Spread for Pad {
    fn apply(&self, x: i32) -> i32 {
        if x > 255 {
            255
        } else if x < 0 {
            0
        } else {
            x
        }
    }
}
  • 将超出范围的值截断到边界

  • x > 255 → 返回255

  • x < 0 → 返回0

  • 否则返回原值

Repeat模式
rust 复制代码
impl Spread for Repeat {
    fn apply(&self, x: i32) -> i32 {
        x & 255
    }
}
  • 使用位运算实现模256的效果

  • 相当于x % 256,但效率更高

  • 例如:256 → 0, 257 → 1, -1 → 255

Reflect模式
rust 复制代码
impl Spread for Reflect {
    fn apply(&self, x: i32) -> i32 {
        let sign = (x << 23) >> 31;
        (x ^ sign) & 255
    }
}
  • 实现类似"反射"边界的效果

  • 当x超出范围时,会像镜子一样反射回来

  • 例如:256 → 255, 257 → 254, -1 → 0, -2 → 1

  • 使用位运算技巧高效实现:

    • sign计算x的符号位(0表示正,-1表示负)

    • x ^ sign相当于x取反(当x为负时)

    • 最后& 255确保在0-255范围内

使用场景

这段代码可能用于图像处理中,当颜色值计算超出标准范围时,提供不同的处理策略:

  • Pad: 简单截断,保持颜色在有效范围内

  • Repeat: 循环处理,适合某些纹理或模式重复的场景

  • Reflect: 镜像反射处理,可以创建更平滑的过渡效果

这些模式的选择会影响图像处理边缘效果或颜色溢出的处理方式。

相关推荐
花褪残红青杏小3 小时前
Rust图像处理第18节-分形画布缩放 + 拖拽交互:图像缩放 + f32 性能优化
rust·webassembly·图形学
doiito3 小时前
【开源项目】用 Rust 重构中文 TTS!kokoroi-rs 高性能语音合成引擎介绍
ai·rust
铅笔侠_小龙虾4 小时前
Rust 学习目录
开发语言·学习·rust
铅笔侠_小龙虾11 小时前
Rust 学习(4)-函数与注释
开发语言·学习·rust
前端H13 小时前
Biome & Rolldown:Rust 工具链接管前端基建
开发语言·前端·rust
独孤留白14 小时前
从C到Rust:struct Cell / RefCell 线程内局部可变性
rust
Kapaseker14 小时前
Rust 是如何处理异常的
rust·kotlin
铅笔侠_小龙虾16 小时前
Rust 学习(8)-切片类型
学习·rust·c#
程序员爱钓鱼19 小时前
Rust 函数与返回值详解:参数、表达式与返回类型
后端·rust
花褪残红青杏小1 天前
Rust图像处理第17节-Julia 朱利亚分形:拖动常数 c 看图实时变化
rust·webassembly·图形学