基于rust的RGBA颜色混合

一般采用以下脚本。

rust 复制代码
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Pixel {
    pub r: u8,
    pub g: u8,
    pub b: u8,
    pub a: u8,
}

impl Pixel {
    pub fn blend(p1: Pixel, p2: Pixel) -> Pixel {
        let a1 = p1.a as u32;
        let a2 = p2.a as u32;

        let a3 = a2 + (a1 * (255 - a2) >> 8);
        let x = a3 - a1;

        let r = ((p1.r as u32 * a1 + p2.r as u32 * x) / a3) as u8;
        let g = ((p1.g as u32 * a1 + p2.g as u32 * x) / a3) as u8;
        let b = ((p1.b as u32 * a1 + p2.b as u32 * x) / a3) as u8;
        let a = a3 as u8;

        Pixel { r, g, b, a }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn basic() {
        let p1 = Pixel { r: 255, g: 0, b: 0, a: 128 };
        let p2 = Pixel { r: 0, g: 255, b: 0, a: 255 };
        let blended = Pixel::blend(p1, p2);
        println!("{:?}", blended);
    }
}

若透明像素较多,考虑以下脚本。

rust 复制代码
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Pixel {
    pub r: u8,
    pub g: u8,
    pub b: u8,
    pub a: u8,
}

impl Pixel {
    pub fn blend(p1: Pixel, p2: Pixel) -> Pixel {
        let a1 = p1.a as u32;
        let a2 = p2.a as u32;

        if a1 == 0 { return p2; }
        if a2 == 0 { return p1; }

        let a3 = a2 + (a1 * (255 - a2) >> 8);
        let x = a3 - a1;

        let r = ((p1.r as u32 * a1 + p2.r as u32 * x) / a3) as u8;
        let g = ((p1.g as u32 * a1 + p2.g as u32 * x) / a3) as u8;
        let b = ((p1.b as u32 * a1 + p2.b as u32 * x) / a3) as u8;
        let a = a3 as u8;

        Pixel { r, g, b, a }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn basic() {
        let p1 = Pixel { r: 255, g: 0, b: 0, a: 128 };
        let p2 = Pixel { r: 0, g: 255, b: 0, a: 255 };
        let blended = Pixel::blend(p1, p2);
        println!("{:?}", blended);
    }
}
相关推荐
元Y亨H2 小时前
RustDesk 自建远程桌面服务器部署指南
rust
@大迁世界15 小时前
相信我兄弟:Cloudflare Rust 的 .unwrap() 方法在 330 多个数据中心引发了恐慌
开发语言·后端·rust
2***B44916 小时前
Rust在系统编程中的内存安全
开发语言·后端·rust
U***e6316 小时前
Rust错误处理最佳实践
开发语言·后端·rust
疏狂难除20 小时前
随便玩玩lldb (二)
开发语言·后端·rust
Rust语言中文社区1 天前
【Rust日报】 丰田“先锋”选择了 Rust
开发语言·后端·rust
邹小邹-AI1 天前
Rust + 前端:下一个十年的“王炸组合”
开发语言·前端·rust
芳草萋萋鹦鹉洲哦1 天前
【tauri+rust】App会加载白屏,有时显示在左上角显示一小块,如何优化
开发语言·后端·rust
zengyuhan5031 天前
Windows BLE 开发指南(Rust windows-rs)
前端·rust