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).to_rgba8(), [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_rgba8(255, 0, 0, 255),
        Color::from_rgba8(0, 255, 0, 255),
    ])
    .build()?;

assert_eq!(g.at(0.0).to_rgba8(), [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 rgba = grad.at(x as f64 / width as f64).to_rgba8();
        *pixel = image::Rgba(rgba);
    }

    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 rgba = grad.at(remap(t, -0.5, 0.5, 0.0, 1.0)).to_rgba8();
        *pixel = image::Rgba(rgba);
    }

    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

Functions