get_value 返回 `f64` 而不是 `[u8; 4]`

时间:2020-12-26 04:06:24

标签: rust

我正在使用 noise 板条箱,但无法理解如何将其 Color type 转换为 RGB 值。

noise = "0.7.0"
pub type Color = [u8; 4];

我正在尝试使用 get_value() 函数,此处在 docs 中显示为:

pub fn get_value(&self, x: usize, y: usize) -> Color {
    let (width, height) = self.size;

    if x < width && y < height {
        self.map[x + y * width]
    } else {
        self.border_color
    }
}

get_value() 是为 PlaneMapBuilder 实现的。所以我希望 PlaneMapBuilder::get_value(x,y) 返回格式为 [r,g,b,a] 的东西,但这不会发生:

extern crate noise;

use noise::{utils::*, Billow};

fn main() {
    let mut my_noise = PlaneMapBuilder::new(&Billow::new()).build();
    let my_val = my_noise.get_value(1,1);
    println!("{}", my_val.to_string());
    ///returns something like -0.610765515150546, not a [u8;4] as I would expect
}

docs 中,我看到了 add_gradient_point() 的这个定义,它以 Color 作为参数:

pub fn add_gradient_point(mut self, pos: f64, color: Color) -> Self {
    // check to see if the vector already contains the input point.
    if !self
        .gradient_points
        .iter()
        .any(|&x| (x.pos - pos).abs() < std::f64::EPSILON)
    {
        // it doesn't, so find the correct position to insert the new
        // control point.
        let insertion_point = self.find_insertion_point(pos);

        // add the new control point at the correct position.
        self.gradient_points
            .insert(insertion_point, GradientPoint { pos, color });
    }

    self
}

这里他们使用了我期望的 [u8; 4] 类型的 Color 结构:

let jade_gradient = ColorGradient::new()
.clear_gradient()
    .add_gradient_point(-1.000, [24, 146, 102, 255])
    .add_gradient_point(0.000, [78, 154, 115, 255])

什么可以解释这种行为?

1 个答案:

答案 0 :(得分:3)

<块引用>

get_value() 是为 PlaneMapBuilder

实现的

PlaneMapBuilder“实现”get_value() 是正确的。但是,它不是来自 NoiseImageget_value()。它实际上是 NoiseMap,其中它的 get_value() 返回 f64 而不是 Color


根据您想要的“颜色”类型,您可以改为使用 ImageRenderer 并使用 &my_noise 调用其 render() 方法,该方法返回 NoiseImage .

// noise = "0.7.0"
use noise::{utils::*, Billow};

fn main() {
    let my_noise = PlaneMapBuilder::new(&Billow::new()).build();
    let image = ImageRenderer::new().render(&my_noise);
    let my_val = image.get_value(1, 1);
    println!("{:?}", my_val);
    // Prints: `[18, 18, 18, 255]`
}

<块引用>

这里他们使用了我期望的 [u8; 4] 类型的 Color 结构

需要明确的是,在这种情况下,它们是相同的。简而言之,type 关键字允许您为现有类型定义新的“type aliases”。本质上,您可以为复杂类型指定一个简写名称。但是,它们仍然是同一类型。