Rust:如何迭代 RGB 轮?

问题描述 投票:0回答:1

我找不到实现某种 RGB 迭代器的库,该迭代器从红色 (255-0-0) 迭代到黄色 (255-255-0) 等。是否可以实现它?它的结构应该实现

Iter<T=(f64,f64,f64)>
,也许它包含
max_iters
来改变它的长度。

在库中搜索函数/方法,我还没有找到它的实现

rust colors
1个回答
0
投票

我已经实现了:

pub struct RainbowIterator {
    max: usize,
    current: usize,
}

impl RainbowIterator {
    pub fn new(max: usize) -> Self {
        Self { max, current: 0 }
    }
}

impl Iterator for RainbowIterator {
    type Item = (u8, u8, u8);
    fn next(&mut self) -> Option<Self::Item> {
        let mut ret = (255, 255, 255);
        if self.current >= self.max {
            return None;
        }
        let progress: f64 = self.current as f64 / self.max as f64;
        let subprogress = progress % (1.0 / 6.0);
        let phase = (progress * 6.0) as u8;
        if phase == 0 {
            ret.2 *= 0;
            ret.1 = (255.0 * progress) as u8;
        } else if phase == 1 {
            ret.2 *= 0;
            ret.0 = 255 - (255.0 * progress) as u8;
        } else if phase == 2 {
            ret.0 *= 0;
            ret.2 = (255.0 * progress) as u8;
        } else if phase == 3 {
            ret.0 *= 0;
            ret.1 = 255 - (255.0 * progress) as u8;
        } else if phase == 4 {
            ret.1 *= 0;
            ret.0 = (255.0 * progress) as u8;
        } else {
            ret.1 *= 0;
            ret.2 = 255 - (255.0 * progress) as u8;
        }
        self.current += 1;
        return Some(ret);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.