Crate colorgrad[][src]

Expand description

Overview

Rust color scales library for data visualization, charts, games, maps, generative art and others.

Usage

Using preset gradient:

let g = colorgrad::rainbow();

assert_eq!(g.domain(), (0.0, 1.0)); // all preset gradients are in the domain [0..1]
assert_eq!(g.at(0.5).rgba_u8(), (175, 240, 91, 255));
assert_eq!(g.at(0.5).to_hex_string(), "#aff05b");

Custom gradient:

use colorgrad::Color;

let g = colorgrad::CustomGradient::new()
    .colors(&[
        Color::from_rgb_u8(255, 0, 0),
        Color::from_rgb_u8(0, 255, 0),
    ])
    .build()?;

assert_eq!(g.at(0.0).rgba_u8(), (255, 0, 0, 255));
assert_eq!(g.at(0.0).to_hex_string(), "#ff0000");
assert_eq!(g.at(1.0).to_hex_string(), "#00ff00");

Examples

Gradient Image

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let grad = colorgrad::CustomGradient::new()
        .html_colors(&["deeppink", "gold", "seagreen"])
        .build()?;

    let width = 1500;
    let height = 70;

    let mut imgbuf = image::ImageBuffer::new(width, height);

    for (x, _, pixel) in imgbuf.enumerate_pixels_mut() {
        let (r, g, b, a) = grad.at(x as f64 / width as f64).rgba_u8();
        *pixel = image::Rgba([r, g, b, a]);
    }

    imgbuf.save("gradient.png")?;
    Ok(())
}

Example output:

img

Colored Noise

use noise::NoiseFn;

fn main() {
    let scale = 0.015;

    let grad = colorgrad::rainbow().sharp(5, 0.15);
    let ns = noise::OpenSimplex::new();
    let mut imgbuf = image::ImageBuffer::new(600, 350);

    for (x, y, pixel) in imgbuf.enumerate_pixels_mut() {
        let t = ns.get([x as f64 * scale, y as f64 * scale]);
        let (r, g, b, a) = grad.at(remap(t, -0.5, 0.5, 0.0, 1.0)).rgba_u8();
        *pixel = image::Rgba([r, g, b, a]);
    }

    imgbuf.save("noise.png").unwrap();
}

// Map t which is in range [a, b] to range [c, d]
fn remap(t: f64, a: f64, b: f64, c: f64, d: f64) -> f64 {
    (t - a) * ((d - c) / (b - a)) + c
}

Example output:

img

Preset Gradients

colorgrad::cubehelix_default() img

colorgrad::turbo() img

colorgrad::spectral() img

colorgrad::viridis() img

colorgrad::magma() img

colorgrad::rainbow() img

colorgrad::sinebow() img

See more complete gradient preview and examples at Github.

Structs

The color

Create custom gradient

The gradient

Enums

Color blending mode

Interpolation mode

Functions