【学Rust写CAD】20 平铺模式结构体(spread.rs)
这个 Spread。rs文件定义了渐变超出定义区域时的扩展方式,通常用于处理渐变在边界之外的行为。
源码
//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)的数值。
主要组成部分
- 模式定义
定义了三个空结构体,分别表示不同的处理模式:
pub struct Pad; // Pad模式
pub struct Reflect; // Reflect模式
pub struct Repeat; // Repeat模式
这些结构体都是空结构体(零大小类型),仅用作标记类型(tag types)来实现不同的行为。
- Spread trait
定义了一个trait Spread,它有一个方法apply,接受一个i32参数并返回处理后的i32值:
trait Spread {fn apply(&self, x: i32) -> i32;
}
- 不同模式的实现
Pad模式
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模式
impl Spread for Repeat {fn apply(&self, x: i32) -> i32 {x & 255}
}
-
使用位运算实现模256的效果
-
相当于x % 256,但效率更高
-
例如:256 → 0, 257 → 1, -1 → 255
Reflect模式
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: 镜像反射处理,可以创建更平滑的过渡效果
这些模式的选择会影响图像处理边缘效果或颜色溢出的处理方式。