Crate colorgrad

Source
Expand description

§Overview

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

§Usage

Using preset gradient:

use colorgrad::Gradient;
let g = colorgrad::preset::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, Gradient};

let g = colorgrad::GradientBuilder::new()
    .colors(&[
        Color::from_rgba8(255, 0, 0, 255),
        Color::from_rgba8(0, 255, 0, 255),
    ])
    .build::<colorgrad::LinearGradient>()?;

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

use colorgrad::Gradient;

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

    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 f32 / width as f32).to_rgba8();
        *pixel = image::Rgba(rgba);
    }

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

Example output:

img

§Colored Noise

use colorgrad::Gradient;
use noise::NoiseFn;

fn main() {
    let scale = 0.015;

    let grad = colorgrad::preset::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 f32 * scale, y as f32 * 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: f32, a: f32, b: f32, c: f32, d: f32) -> f32 {
    (t - a) * ((d - c) / (b - a)) + c
}

Example output:

img

§Preset Gradients

colorgrad::preset::cubehelix_default() img

colorgrad::preset::turbo() img

colorgrad::preset::spectral() img

colorgrad::preset::viridis() img

colorgrad::preset::magma() img

colorgrad::preset::rainbow() img

colorgrad::preset::sinebow() img

See more complete gradient preview and examples at Github.

Modules§

preset
Preset Gradients

Structs§

BasisGradient
CatmullRomGradient
Color
The color
GimpGradient
Parse GIMP gradient (ggr)
GradientBuilder
Create custom gradient
InverseGradient
A gradient that inverts the gradient of another gradient.
LinearGradient
ParseGgrError
SharpGradient

Enums§

BlendMode
Color blending mode
GradientBuilderError
ParseColorError

Traits§

CloneGradient
Gradient