colorgrad Rust Library

repository·master·Indexed 18 days ago

https://github.com/mazznoer/colorgrad-rs

A Rust library for creating and manipulating color scales and gradients for data visualization, games, generative art, and maps. It features a GradientBuilder for custom gradients (Linear, CatmullRom, Basis), support for CSS and HTML color formats, and a collection of preset Diverging, Sequential, and Cyclical gradients. The library supports various blending modes including Oklab and Lab, and provides utilities for sampling colors, generating sequences, and creating hard-edged gradients.

Tokens
7.7K
Snippets
30
Records
38
Agent score
61%

What's inside colorgrad

  1. Configure Domain and Color Positions

    master

    The default domain for a gradient is [0.0, 1.0]. You can use the .domain() method to change the range or to assign specific positions to the colors provided in the builder.

    • To set a range like [0.0, 100.0], pass &[0.0, 100.0] to .domain().
    • To assign specific colors to specific points in the domain, pass a slice containing those points, e.g., &[0.0, 0.7, 1.0].
    // Set domain to [0..100]
    let g = colorgrad::GradientBuilder::new()
        .html_colors(&["deeppink", "gold", "seagreen"])
        .domain(&[0.0, 100.0])
        .build::<colorgrad::LinearGradient>()?;
    
    // Set exact positions for colors within the default [0..1] domain
    let g = colorgrad::GradientBuilder::new()
        .html_colors(&["deeppink", "gold", "seagreen"])
        .domain(&[0.0, 0.7, 1.0])
        .build::<colorgrad::LinearGradient>()?;
  2. Use preset gradients in colorgrad

    master

    colorgrad provides a collection of predefined gradients categorized by their color distribution patterns (Diverging, Sequential, Cyclical). All preset gradients operate within a default domain of [0..1] and use Uniform B-splines for color interpolation.

    You can access these presets via the colorgrad::preset module. Once a gradient is retrieved, you can sample colors at specific positions using .at(pos) or generate a sequence of colors using .colors(n).

    use colorgrad::Gradient;
    
    // Get a preset gradient
    let g = colorgrad::preset::viridis();
    
    // Check the domain (usually 0.0 to 1.0)
    assert_eq!(g.domain(), (0.0, 1.0));
    
    // Sample a single color at a specific position and convert to CSS hex
    println!("{}", g.at(0.27).to_css_hex());
    
    // Generate a sequence of 35 colors and print their RGBA8 values
    for color in g.colors(35) {
        println!("{:?}", color.to_rgba8());
    }
  3. Install colorgrad

    master

    Add colorgrad to your Cargo.toml to use the library in your Rust project.

    Note that the library has optional features:

    • named-colors: Enables parsing from CSS named colors.
    • preset: Enables access to preset gradients.
    • ggr: Enables parsing GIMP gradient format.

    You can disable default features using default-features = false in your dependency configuration.

    colorgrad = "0.9.0"
  4. Create a custom gradient with GradientBuilder

    master

    Use colorgrad::GradientBuilder to construct custom gradients. You must specify a gradient type (e.g., LinearGradient, CatmullRomGradient, BasisGradient) when calling .build().

    Common builder methods include:

    • .colors(&[Color]): Set a sequence of Color objects.
    • .html_colors(&[&str]): Set colors using web formats (hex, named colors, rgb, hsl, etc.).
    • .css(&str): Set colors using a CSS gradient string.
    • .domain(&[f32]): Set the domain and/or specific color positions.
    • .mode(BlendMode): Set the blending mode (e.g., BlendMode::Rgb).
    // Basic default gradient
    let g = colorgrad::GradientBuilder::new().build::<colorgrad::LinearGradient>()?;
    
    // Custom colors using Color objects
    let g = colorgrad::GradientBuilder::new()
        .colors(&[
            Color::from_rgba8(0, 206, 209, 255),
            Color::from_hsva(50.0, 1.0, 1.0, 1.0),
        ])
        .build::<colorgrad::LinearGradient>()?;
    
    // Using CSS gradient format
    let g = colorgrad::GradientBuilder::new()
        .css("blue, cyan, gold, purple 70%, tomato 70%, 90%, #ff0")
        .build::<colorgrad::CatmullRomGradient>()?;
  5. Implement the Gradient trait

    master

    The Gradient trait is the core abstraction in colorgrad. Any type implementing this trait can be used as a color gradient. You can implement it for your own custom types to define how colors are sampled at specific positions.

    To implement Gradient, you must provide the at(&self, t: f32) -> Color method, which returns the color at position t (typically in the range [0.0, 1.0]).

    Once implemented, you gain access to several helper methods:

    • at(t): Get color at position t.
    • repeat_at(t): Get color at position t using repeat mode (cycles through the domain).
    • reflect_at(t): Get color at position t using reflect mode (mirrors the domain).
    • domain(): Returns the gradient's min and max bounds (defaults to (0.0, 1.0)).
    • colors(n): Returns an iterator for n colors evenly spaced across the gradient.
    • sharp(segment, smoothness): Converts the gradient into a SharpGradient with hard edges.
    • inverse(): Returns a new gradient that inverts the colors.
    • boxed(): Converts the gradient into a Box<dyn Gradient> for use in collections or dynamic returns.
    use colorgrad::{Color, Gradient};
    
    #[derive(Clone)]
    struct MyRedGradient {}
    
    impl Gradient for MyRedGradient {
        fn at(&self, t: f32) -> Color {
            Color::new(1.0, 0.0, 0.0, 1.0)
        }
    }
    
    let g = MyRedGradient{};
    assert_eq!(g.domain(), (0.0, 1.0));
    assert_eq!(g.at(0.1).to_css_hex().to_string(), "#ff0000");
  6. Initialize gradients using HTML or CSS color formats

    master

    The GradientBuilder supports initializing gradients from string-based color formats:

    • HTML colors: Pass a slice of strings containing names (e.g., "red"), hex codes (e.g., "#abc"), or other CSS color strings.
    • CSS gradient strings: Pass a single string representing a CSS gradient definition (e.g., "gold, 35%, #f00").
    // Using HTML color format
    let g_html = GradientBuilder::new()
        .html_colors(&["red", "#abc", "gold"])
        .build::<LinearGradient>()?;
    
    // Using CSS gradient format
    let g_css = GradientBuilder::new()
        .css("gold, 35%, #f00")
        .build::<LinearGradient>()?;
  7. Use preset gradients

    master

    You can quickly access pre-defined color scales using the colorgrad::preset module. All preset gradients operate on a domain of [0.0, 1.0]. You can sample colors at specific points using .at(t) or iterate through a sequence of colors using .colors(n).

    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_css_hex().to_string(), "#aff05b");
    
    for color in g.colors(20) {
        println!("{:?}", color.to_rgba8());
    }
  8. Sample colors from a Gradient

    master

    Once you have a Gradient, you can retrieve colors at specific points or generate a sequence of colors.

    Accessing colors at positions

    • at(pos): Returns the color at the given position.
    • repeat_at(pos): Returns the color using a repeating spread mode.
    • reflect_at(pos): Returns the color using a reflecting spread mode.

    Generating sequences

    • colors(n): Returns an iterator of n colors evenly spaced across the gradient.
    use colorgrad::Gradient;
    
    let grad = colorgrad::preset::blues();
    
    // Get single color
    let c = grad.at(0.5).to_rgba8();
    
    // Get n colors evenly spaced
    for c in grad.colors(10) {
        println!("{}", c.to_css_hex());
    }
  9. Create hard-edged (sharp) gradients

    master

    You can convert a smooth gradient into a hard-edged gradient using the .sharp(segments, smoothness) method. This creates a stepped effect.

    • segments: The number of discrete color segments.
    • smoothness: A value (typically 0.0 to 1.0) controlling the transition smoothness between segments.
    // Create a rainbow gradient with 11 sharp segments and 0 smoothness
    let g = colorgrad::preset::rainbow().sharp(11, 0.0);
  10. Parse GIMP Gradients

    master

    If the ggr feature is enabled, you can parse .ggr files using GimpGradient::new. This requires a reader (like BufReader) and a fallback Color to use for missing data.

    use colorgrad::{Color, GimpGradient};
    use std::fs::File;
    use std::io::BufReader;
    
    let input = File::open("examples/Abstract_1.ggr")?;
    let buf = BufReader::new(input);
    let col = Color::default();
    let grad = GimpGradient::new(buf, &col, &col)?;
    
    assert_eq!(grad.name(), "Abstract 1");
  11. Reference: Sequential preset gradients

    master

    Sequential gradients are designed for data that moves from low to high values in a single direction. They are split into Single-Hue and Multi-Hue categories.

    Single Hue

    Focuses on variations of a single color:

    • colorgrad::preset::blues()
    • colorgrad::preset::greens()
    • colorgrad::preset::greys()
    • colorgrad::preset::oranges()
    • colorgrad::preset::purples()
    • colorgrad::preset::reds()

    Multi-Hue

    Transitions through multiple colors for better perceptual differentiation:

    • colorgrad::preset::turbo()
    • colorgrad::preset::viridis()
    • colorgrad::preset::inferno()
    • colorgrad::preset::magma()
    • colorgrad::preset::plasma()
    • colorgrad::preset::cividis()
    • colorgrad::preset::warm()
    • colorgrad::preset::cool()
    • colorgrad::preset::cubehelix_default()
    • colorgrad::preset::bu_gn()
    • colorgrad::preset::bu_pu()
    • colorgrad::preset::gn_bu()
    • colorgrad::preset::or_rd()
    • colorgrad::preset::pu_bu_gn()
    • colorgrad::preset::pu_bu()
    • colorgrad::preset::pu_rd()
    • colorgrad::preset::rd_pu()
    • colorgrad::preset::yl_gn_bu()
    • colorgrad::preset::yl_gn()
    • colorgrad::preset::yl_or_br()
    • colorgrad::preset::yl_or_rd()
  12. Reference: Diverging preset gradients

    master

    Diverging gradients are useful for data that has a meaningful midpoint (e.g., zero or neutral values) and moves toward two different extremes.

    Available presets:

    • colorgrad::preset::br_bg()
    • colorgrad::preset::pr_gn()
    • colorgrad::preset::pi_yg()
    • colorgrad::preset::pu_or()
    • colorgrad::preset::rd_bu()
    • colorgrad::preset::rd_gy()
    • colorgrad::preset::rd_yl_bu()
    • colorgrad::preset::rd_yl_gn()
    • colorgrad::preset::spectral()