### Generate Gradient Images in Rust Source: https://context7.com/mazznoer/colorgrad-rs/llms.txt Shows how to create gradient images using the `colorgrad` and `image` crates. Includes examples for generating a custom gradient image from HTML colors, creating a sharp gradient using a preset, and comparing different interpolation modes (linear, CatmullRom, basis) by saving images for each. ```rust use colorgrad::Gradient; fn main() -> Result<(), Box> { let width = 1300u32; let height = 70u32; // Create a custom gradient let grad = colorgrad::GradientBuilder::new() .html_colors(&["deeppink", "gold", "seagreen"]) .build::()?; // Generate gradient image let imgbuf = image::ImageBuffer::from_fn(width, height, |x, _| { let t = x as f32 / width as f32; image::Rgba(grad.at(t).to_rgba8()) }); imgbuf.save("gradient.png")?; // Generate sharp gradient image let sharp_grad = colorgrad::preset::rainbow().sharp(11, 0.0); let imgbuf = image::ImageBuffer::from_fn(width, height, |x, _| { image::Rgba(sharp_grad.at(x as f32 / width as f32).to_rgba8()) }); imgbuf.save("sharp-gradient.png")?; // Generate comparison of all interpolation modes let colors = &["#C41189", "#00BFFF", "#FFD700"]; let gradients: Vec<(&str, Box)> = vec![ ("linear", colorgrad::GradientBuilder::new() .html_colors(colors) .build::()?.boxed()), ("catmull-rom", colorgrad::GradientBuilder::new() .html_colors(colors) .build::()?.boxed()), ("basis", colorgrad::GradientBuilder::new() .html_colors(colors) .build::()?.boxed()), ]; for (name, grad) in gradients { let imgbuf = image::ImageBuffer::from_fn(width, height, |x, _| { image::Rgba(grad.at(x as f32 / width as f32).to_rgba8()) }); imgbuf.save(format!("gradient-{}.png", name))?; } Ok(()) } ``` -------------------------------- ### Create and Convert Colors in Rust Source: https://context7.com/mazznoer/colorgrad-rs/llms.txt Demonstrates creating `Color` instances from RGBA8, normalized float values, and HSVA. Also shows parsing colors from various string formats (hex, named, rgb, hsl) and converting `Color` objects to different representations like RGBA8, array, hex, and HSVA. Includes examples for linear RGB, Oklab, and Lab color spaces, and shows the default transparent black color. ```rust use colorgrad::Color; fn main() { // Create colors from different formats let rgba8 = Color::from_rgba8(255, 128, 64, 255); let normalized = Color::new(1.0, 0.5, 0.25, 1.0); // r, g, b, a as 0.0-1.0 let hsva = Color::from_hsva(30.0, 0.75, 1.0, 1.0); // h: 0-360, s,v,a: 0-1 // Parse from string let hex = csscolorparser::parse("#ff8040").unwrap(); let named = csscolorparser::parse("coral").unwrap(); let rgb_func = csscolorparser::parse("rgb(255, 128, 64)").unwrap(); let hsl_func = csscolorparser::parse("hsl(30, 100%, 60%)").unwrap(); // Convert to different formats let color = Color::from_rgba8(255, 128, 64, 255); println!("RGBA8: {:?}", color.to_rgba8()); // [255, 128, 64, 255] println!("Array: {:?}", color.to_array()); // [1.0, 0.502, 0.251, 1.0] println!("Hex: {}", color.to_css_hex()); // #ff8040 println!("HSVA: {:?}", color.to_hsva()); // [h, s, v, a] // Linear RGB (for physically accurate blending) let linear = Color::from_linear_rgba(0.5, 0.25, 0.1, 1.0); // Oklab (perceptually uniform color space) let oklab = Color::from_oklaba(0.7, 0.1, 0.05, 1.0); // Lab color space let lab = Color::from_laba(70.0, 20.0, 30.0, 1.0); // Default color is transparent black let default = Color::default(); println!("Default: {:?}", default.to_rgba8()); // [0, 0, 0, 255] } ``` -------------------------------- ### Build Gradient with CSS Gradient String Source: https://github.com/mazznoer/colorgrad-rs/blob/master/README.md Parses and builds a gradient from a CSS gradient string format. This example uses `CatmullRomGradient`. ```rust let g = colorgrad::GradientBuilder::new() .css("blue, cyan, gold, purple 70%, tomato 70%, 90%, #ff0") .build::()?; ``` -------------------------------- ### Retrieve Gradient Domain Source: https://github.com/mazznoer/colorgrad-rs/blob/master/README.md Returns the start and end domain values of the gradient. ```rust let grad = colorgrad::preset::rainbow(); assert_eq!(grad.domain(), (0.0, 1.0)); ``` -------------------------------- ### Get Default Gradient Domain Source: https://github.com/mazznoer/colorgrad-rs/blob/master/README.md Retrieves the default domain of a gradient, which is typically [0.0, 1.0]. ```rust let g = colorgrad::GradientBuilder::new() .html_colors(&["deeppink", "gold", "seagreen"]) .build::()?; assert_eq!(g.domain(), (0.0, 1.0)); ``` -------------------------------- ### Access and Use Preset Gradients in Rust Source: https://github.com/mazznoer/colorgrad-rs/blob/master/PRESET.md Demonstrates loading a preset gradient, verifying its domain, and extracting colors or CSS hex values. ```rust use colorgrad::Gradient; let g = colorgrad::preset::viridis(); assert_eq!(g.domain(), (0.0, 1.0)); println!("{}", g.at(0.27).to_css_hex()); for color in g.colors(35) { println!("{:?}", color.to_rgba8()); } ``` -------------------------------- ### Sample Gradients with at, repeat_at, and reflect_at Source: https://context7.com/mazznoer/colorgrad-rs/llms.txt Demonstrates sampling colors at specific positions using clamping, tiling, and mirroring behaviors. ```rust use colorgrad::Gradient; fn main() { let grad = colorgrad::preset::blues(); // at() - clamps values outside domain to endpoints assert_eq!(grad.at(0.0).to_rgba8(), [247, 251, 255, 255]); assert_eq!(grad.at(0.5).to_rgba8(), [109, 174, 213, 255]); assert_eq!(grad.at(1.0).to_rgba8(), [8, 48, 107, 255]); // Values outside [0,1] are clamped assert_eq!(grad.at(-0.5).to_rgba8(), grad.at(0.0).to_rgba8()); assert_eq!(grad.at(1.5).to_rgba8(), grad.at(1.0).to_rgba8()); // repeat_at() - tiles the gradient (sawtooth pattern) // t=1.3 becomes t=0.3 println!("repeat_at(1.3): {}", grad.repeat_at(1.3).to_css_hex()); println!("at(0.3): {}", grad.at(0.3).to_css_hex()); // reflect_at() - mirrors at boundaries (triangle wave) // t=1.3 becomes t=0.7 (reflected) println!("reflect_at(1.3): {}", grad.reflect_at(1.3).to_css_hex()); println!("at(0.7): {}", grad.at(0.7).to_css_hex()); // Within domain, all three methods return the same color assert_eq!(grad.at(0.3).to_rgba8(), grad.repeat_at(0.3).to_rgba8()); assert_eq!(grad.at(0.3).to_rgba8(), grad.reflect_at(0.3).to_rgba8()); } ``` -------------------------------- ### Build Basic Linear Gradient Source: https://github.com/mazznoer/colorgrad-rs/blob/master/README.md Creates a default linear gradient. Ensure the `colorgrad` crate is added to your Cargo.toml. ```rust let g = colorgrad::GradientBuilder::new().build::()?; ``` -------------------------------- ### Build Gradient with Named HTML Colors Source: https://github.com/mazznoer/colorgrad-rs/blob/master/README.md Constructs a gradient using standard CSS named colors. ```rust let g = colorgrad::GradientBuilder::new() .html_colors(&["gold", "hotpink", "darkturquoise"]) .build::()?; ``` -------------------------------- ### Create Hard-Edged Gradients with sharp() Source: https://context7.com/mazznoer/colorgrad-rs/llms.txt Converts gradients into posterized segments with configurable transition smoothness. ```rust use colorgrad::Gradient; fn main() -> Result<(), Box> { let rainbow = colorgrad::preset::rainbow(); // Hard-edged gradient with 11 segments and no smoothness let sharp = rainbow.sharp(11, 0.0); // Hard-edged with some smoothness (softer transitions) let smooth_sharp = rainbow.sharp(11, 0.15); // Very smooth transitions let very_smooth = rainbow.sharp(11, 0.5); // Sample the sharp gradient for t in (0..=20).map(|i| i as f32 / 20.0) { println!("t={:.2}: {}", t, sharp.at(t).to_css_hex()); } // Create a custom gradient and make it sharp let custom = colorgrad::GradientBuilder::new() .html_colors(&["#ff0000", "#00ff00", "#0000ff"]) .build::()?; let custom_sharp = custom.sharp(6, 0.1); println!("\nCustom sharp gradient:"); for color in custom_sharp.colors(12) { println!("{}", color.to_css_hex()); } Ok(()) } ``` -------------------------------- ### Generate Gradient Image Source: https://github.com/mazznoer/colorgrad-rs/blob/master/README.md Uses the image crate to render a gradient to a PNG file. ```rust use colorgrad::Gradient; fn main() -> Result<(), Box> { let width = 1300.0; let height = 70.0; // custom gradient let grad = colorgrad::GradientBuilder::new() .html_colors(&["deeppink", "gold", "seagreen"]) .build::()?; let imgbuf = image::ImageBuffer::from_fn(width as u32, height as u32, |x, _| { image::Rgba(grad.at(x as f32 / width).to_rgba8()) }); imgbuf.save("gradient.png")?; Ok(()) } ``` -------------------------------- ### Sample Colors at Positions Source: https://github.com/mazznoer/colorgrad-rs/blob/master/README.md Samples colors at specific positions using standard, repeat, and reflect spread modes. ```rust use colorgrad::Gradient; let grad = colorgrad::preset::blues(); assert_eq!(grad.at(0.0).to_rgba8(), [247, 251, 255, 255]); assert_eq!(grad.at(0.5).to_rgba8(), [109, 174, 213, 255]); assert_eq!(grad.at(1.0).to_rgba8(), [8, 48, 107, 255]); assert_eq!(grad.at(0.3).to_rgba8(), grad.repeat_at(0.3).to_rgba8()); assert_eq!(grad.at(0.3).to_rgba8(), grad.reflect_at(0.3).to_rgba8()); assert_eq!(grad.at(0.7).to_rgba8(), grad.repeat_at(0.7).to_rgba8()); assert_eq!(grad.at(0.7).to_rgba8(), grad.reflect_at(0.7).to_rgba8()); ``` -------------------------------- ### Configure Gradient Interpolation Mode Source: https://github.com/mazznoer/colorgrad-rs/blob/master/README.md Creates a gradient using the Basis interpolation mode. ```rust let g = colorgrad::GradientBuilder::new() .html_colors(&["#C41189", "#00BFFF", "#FFD700"]) .build::()?; ``` -------------------------------- ### Setting Gradient Blending Mode Source: https://context7.com/mazznoer/colorgrad-rs/llms.txt The `mode()` method specifies how colors are interpolated. Options include `Rgb`, `LinearRgb` (physically accurate), `Oklab` (perceptually uniform), and `Lab`. ```rust use colorgrad::{Gradient, GradientBuilder, LinearGradient, BlendMode}; fn main() -> Result<(), Box> { let colors = &["#FFF", "#00F"]; // RGB blending (default) let rgb = GradientBuilder::new() .html_colors(colors) .mode(BlendMode::Rgb) .build::()?; // Linear RGB blending (physically accurate) let linear_rgb = GradientBuilder::new() .html_colors(colors) .mode(BlendMode::LinearRgb) .build::()?; // Oklab blending (perceptually uniform) let oklab = GradientBuilder::new() .html_colors(colors) .mode(BlendMode::Oklab) .build::()?; // Lab blending let lab = GradientBuilder::new() .html_colors(colors) .mode(BlendMode::Lab) .build::()?; // Compare midpoint colors println!("RGB midpoint: {}", rgb.at(0.5).to_css_hex()); println!("Linear RGB midpoint: {}", linear_rgb.at(0.5).to_css_hex()); println!("Oklab midpoint: {}", oklab.at(0.5).to_css_hex()); println!("Lab midpoint: {}", lab.at(0.5).to_css_hex()); Ok(()) } ``` -------------------------------- ### Set Exact Color Positions within [15..80] Domain Source: https://github.com/mazznoer/colorgrad-rs/blob/master/README.md Specifies exact positions for colors within a custom domain ranging from 15.0 to 80.0. ```rust let g = colorgrad::GradientBuilder::new() .html_colors(&["deeppink", "gold", "seagreen"]) .domain(&[15.0, 30.0, 80.0]) .build::()?; assert_eq!(g.domain(), (15.0, 80.0)); ``` -------------------------------- ### Build Gradient with CSS Color Functions Source: https://github.com/mazznoer/colorgrad-rs/blob/master/README.md Creates a gradient using CSS color functions like rgb() and hsl(). Supports percentage values for color components. ```rust let g = colorgrad::GradientBuilder::new() .html_colors(&["rgb(125,110,221)", "rgb(90%,45%,97%)", "hsl(229,79%,85%)"]) .build::()?; ``` -------------------------------- ### Build Gradient with Hexadecimal HTML Colors Source: https://github.com/mazznoer/colorgrad-rs/blob/master/README.md Creates a gradient using hexadecimal color strings. Supports shorthand and full hex formats. ```rust let g = colorgrad::GradientBuilder::new() .html_colors(&["#C41189", "#00BFFF", "#FFD700"]) .build::()?; ``` -------------------------------- ### Using Different Gradient Interpolation Types Source: https://context7.com/mazznoer/colorgrad-rs/llms.txt Choose from `LinearGradient` (straight lines), `SmoothstepGradient` (ease-in-out), `CatmullRomGradient` (smooth curves through points), and `BasisGradient` (smoothest approximation curves). ```rust use colorgrad::{Gradient, GradientBuilder, LinearGradient, CatmullRomGradient, BasisGradient, SmoothstepGradient}; fn main() -> Result<(), Box> { let colors = &["#C41189", "#00BFFF", "#FFD700"]; // Linear interpolation - straight lines between colors let linear = GradientBuilder::new() .html_colors(colors) .build::()?; // Smoothstep interpolation - ease-in-out transitions let smoothstep = GradientBuilder::new() .html_colors(colors) .build::()?; // Catmull-Rom spline - smooth curves through all points let catmull_rom = GradientBuilder::new() .html_colors(colors) .build::()?; // B-spline basis - smoothest curves (approximating) let basis = GradientBuilder::new() .html_colors(colors) .build::()?; // Sample colors from each interpolation type for t in (0..=10).map(|i| i as f32 / 10.0) { println!( "t={:.1}: linear={} catmull={} basis={}", t, linear.at(t).to_css_hex(), catmull_rom.at(t).to_css_hex(), basis.at(t).to_css_hex() ); } Ok(()) } ``` -------------------------------- ### Build Gradient with Custom RGBA and HSVA Colors Source: https://github.com/mazznoer/colorgrad-rs/blob/master/README.md Constructs a gradient using a mix of RGBA, HSVA, and normalized RGB color values. Requires importing the `Color` struct from `colorgrad`. ```rust use colorgrad::Color; let g = colorgrad::GradientBuilder::new() .colors(&[ Color::from_rgba8(0, 206, 209, 255), Color::from_rgba8(255, 105, 180, 255), Color::new(0.274, 0.5, 0.7, 1.0), Color::from_hsva(50.0, 1.0, 1.0, 1.0), Color::from_hsva(348.0, 0.9, 0.8, 1.0), ]) .build::()?; ``` -------------------------------- ### Parse GIMP Gradient File Source: https://github.com/mazznoer/colorgrad-rs/blob/master/README.md Loads and parses a .ggr file into a gradient object. ```rust 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"); ``` -------------------------------- ### Set Exact Color Positions within [0..1] Domain Source: https://github.com/mazznoer/colorgrad-rs/blob/master/README.md Defines specific positions for each color within the default [0.0, 1.0] domain. ```rust let g = colorgrad::GradientBuilder::new() .html_colors(&["deeppink", "gold", "seagreen"]) .domain(&[0.0, 0.7, 1.0]) .build::()?; assert_eq!(g.domain(), (0.0, 1.0)); ``` -------------------------------- ### Setting Gradient Domain and Color Positions Source: https://context7.com/mazznoer/colorgrad-rs/llms.txt Use the `domain()` method to set the gradient's value range, which defaults to 0.0 to 1.0. You can specify custom ranges or exact positions for each color stop. ```rust use colorgrad::{Gradient, GradientBuilder, LinearGradient}; fn main() -> Result<(), Box> { // Default domain [0..1] let default_domain = GradientBuilder::new() .html_colors(&["deeppink", "gold", "seagreen"]) .build::()?; assert_eq!(default_domain.domain(), (0.0, 1.0)); // Custom domain [0..100] let grad_100 = GradientBuilder::new() .html_colors(&["deeppink", "gold", "seagreen"]) .domain(&[0.0, 100.0]) .build::()?; assert_eq!(grad_100.domain(), (0.0, 100.0)); println!("At 50: {}", grad_100.at(50.0).to_css_hex()); // Custom domain [-1..1] let grad_neg = GradientBuilder::new() .html_colors(&["deeppink", "gold", "seagreen"]) .domain(&[-1.0, 1.0]) .build::()?; assert_eq!(grad_neg.domain(), (-1.0, 1.0)); // Exact position for each color (domain becomes [0..1]) let positioned = GradientBuilder::new() .html_colors(&["deeppink", "gold", "seagreen"]) .domain(&[0.0, 0.7, 1.0]) // gold at 70% .build::()?; // Exact positions with custom domain [15..80] let custom_pos = GradientBuilder::new() .html_colors(&["deeppink", "gold", "seagreen"]) .domain(&[15.0, 30.0, 80.0]) .build::()?; assert_eq!(custom_pos.domain(), (15.0, 80.0)); Ok(()) } ``` -------------------------------- ### Set Gradient Domain to [0..100] Source: https://github.com/mazznoer/colorgrad-rs/blob/master/README.md Configures the gradient's domain to range from 0.0 to 100.0. ```rust let g = colorgrad::GradientBuilder::new() .html_colors(&["deeppink", "gold", "seagreen"]) .domain(&[0.0, 100.0]) .build::()?; assert_eq!(g.domain(), (0.0, 100.0)); ``` -------------------------------- ### Parse GIMP Gradient Files in Rust Source: https://context7.com/mazznoer/colorgrad-rs/llms.txt Load .ggr files using the GimpGradient struct. Requires the ggr feature and providing foreground/background colors for special stops. ```rust use colorgrad::{Color, Gradient, GimpGradient}; use std::fs::File; use std::io::BufReader; fn main() -> Result<(), Box> { // Open and parse a GIMP gradient file let input = File::open("examples/ggr/Abstract_1.ggr")?; let buf = BufReader::new(input); // Provide foreground and background colors for special gradient stops let foreground = Color::from_rgba8(0, 0, 0, 255); let background = Color::from_rgba8(255, 255, 255, 255); let grad = GimpGradient::new(buf, &foreground, &background)?; // Get the gradient name from the file println!("Gradient name: {}", grad.name()); // "Abstract 1" // Use like any other gradient println!("Colors:"); for color in grad.colors(10) { println!("{}", color.to_css_hex()); } // Sample at specific positions let color = grad.at(0.5); println!("Midpoint: {:?}", color.to_rgba8()); Ok(()) } ``` -------------------------------- ### Create Custom Gradients with GradientBuilder Source: https://context7.com/mazznoer/colorgrad-rs/llms.txt Use GradientBuilder to define custom color gradients with Color structs or normalized floats. Supports various color formats like RGBA, HSV, and normalized RGB. The resulting gradient can be built using different interpolation methods like LinearGradient. ```rust use colorgrad::{Color, Gradient, GradientBuilder, LinearGradient, BlendMode}; fn main() -> Result<(), Box> { // Basic gradient with default black-to-white colors let basic = GradientBuilder::new().build::()?; assert_eq!(basic.domain(), (0.0, 1.0)); // Custom gradient using Color structs let grad = GradientBuilder::new() .colors(&[ Color::from_rgba8(0, 206, 209, 255), // Dark turquoise Color::from_rgba8(255, 105, 180, 255), // Hot pink Color::new(0.274, 0.5, 0.7, 1.0), // Using normalized floats Color::from_hsva(50.0, 1.0, 1.0, 1.0), // Using HSV ]) .build::()?; // Get color at position 0.5 let color = grad.at(0.5); println!("RGBA: {:?}", color.to_rgba8()); // [r, g, b, a] println!("Hex: {}", color.to_css_hex()); // #rrggbb Ok(()) } ``` -------------------------------- ### Use Web Color Formats with GradientBuilder Source: https://context7.com/mazznoer/colorgrad-rs/llms.txt The html_colors method accepts various web color formats including hex codes, named colors, and CSS color functions like rgb(), rgba(), hsl(), hsla(), hwb(), and hsv(). Mixed formats are supported. ```rust use colorgrad::{Gradient, GradientBuilder, LinearGradient}; fn main() -> Result<(), Box> { // Using hex colors let hex_grad = GradientBuilder::new() .html_colors(&["#C41189", "#00BFFF", "#FFD700"]) .build::()?; // Using named colors let named_grad = GradientBuilder::new() .html_colors(&["gold", "hotpink", "darkturquoise"]) .build::()?; // Using CSS color functions let css_grad = GradientBuilder::new() .html_colors(&["rgb(125,110,221)", "rgb(90%,45%,97%)", "hsl(229,79%,85%)"]) .build::()?; // Mixed formats work together let mixed = GradientBuilder::new() .html_colors(&["#ff0000", "lime", "rgb(0,0,255)", "hsl(60,100%,50%)"]) .build::()?; for t in [0.0, 0.25, 0.5, 0.75, 1.0] { println!("t={}: {}", t, mixed.at(t).to_css_hex()); } Ok(()) } ``` -------------------------------- ### Configure Gradient Blending Mode Source: https://github.com/mazznoer/colorgrad-rs/blob/master/README.md Sets the blending mode for a gradient using the GradientBuilder. ```rust let g = colorgrad::GradientBuilder::new() .html_colors(&["#FFF", "#00F"]) .mode(colorgrad::BlendMode::Rgb) .build::()?; ``` -------------------------------- ### Set Gradient Domain to [-1..1] Source: https://github.com/mazznoer/colorgrad-rs/blob/master/README.md Sets the gradient's domain to a range from -1.0 to 1.0. ```rust let g = colorgrad::GradientBuilder::new() .html_colors(&["deeppink", "gold", "seagreen"]) .domain(&[-1.0, 1.0]) .build::()?; assert_eq!(g.domain(), (-1.0, 1.0)); ``` -------------------------------- ### Access Preset Gradients in Rust Source: https://context7.com/mazznoer/colorgrad-rs/llms.txt Access various categories of pre-defined gradients, all of which use B-spline interpolation and a domain of [0, 1]. ```rust use colorgrad::Gradient; fn main() { // Diverging gradients (good for data with a meaningful center) let br_bg = colorgrad::preset::br_bg(); let spectral = colorgrad::preset::spectral(); let rd_bu = colorgrad::preset::rd_bu(); // Sequential single-hue (good for ordered data) let blues = colorgrad::preset::blues(); let greens = colorgrad::preset::greens(); let reds = colorgrad::preset::reds(); let greys = colorgrad::preset::greys(); // Sequential multi-hue (perceptually uniform, colorblind-friendly) let viridis = colorgrad::preset::viridis(); let plasma = colorgrad::preset::plasma(); let inferno = colorgrad::preset::inferno(); let magma = colorgrad::preset::magma(); let turbo = colorgrad::preset::turbo(); let cividis = colorgrad::preset::cividis(); // Cyclical (good for periodic data like angles) let rainbow = colorgrad::preset::rainbow(); let sinebow = colorgrad::preset::sinebow(); // Cubehelix variants let warm = colorgrad::preset::warm(); let cool = colorgrad::preset::cool(); let cubehelix = colorgrad::preset::cubehelix_default(); // All presets have domain [0..1] assert_eq!(viridis.domain(), (0.0, 1.0)); assert_eq!(rainbow.domain(), (0.0, 1.0)); // Sample viridis colors println!("Viridis palette:"); for color in viridis.colors(8) { println!("{}", color.to_css_hex()); } } ``` -------------------------------- ### Generate Colored Noise Source: https://github.com/mazznoer/colorgrad-rs/blob/master/README.md Combines noise generation with a gradient to create a colored noise image. ```rust 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(0); let imgbuf = image::ImageBuffer::from_fn(600, 350, |x, y| { let t = ns.get([x as f64 * scale, y as f64 * scale]); image::Rgba(grad.at(norm(t as f32, -0.5, 0.5)).to_rgba8()) }); imgbuf.save("noise.png").unwrap(); } fn norm(t: f32, a: f32, b: f32) -> f32 { (t - a) * (1.0 / (b - a)) } ``` -------------------------------- ### Parse CSS Gradient Syntax with GradientBuilder Source: https://context7.com/mazznoer/colorgrad-rs/llms.txt The css method parses CSS linear-gradient color stop syntax, supporting colors with optional position percentages. It can parse simple gradients, gradients with named colors, and complex gradients with multiple color stops. ```rust use colorgrad::{Gradient, GradientBuilder, CatmullRomGradient, LinearGradient}; fn main() -> Result<(), Box> { // CSS gradient with color stops and positions let grad = GradientBuilder::new() .css("blue, cyan, gold, purple 70%, tomato 70%, 90%, #ff0") .build::()?; // Simple CSS gradient let simple = GradientBuilder::new() .css("#fff, 75%, #00f") .build::()?; // CSS gradient with named colors let named = GradientBuilder::new() .css("gold, 35%, #f00") .build::()?; println!("Color at 0.5: {}", grad.at(0.5).to_css_hex()); Ok(()) } ``` -------------------------------- ### Create Hard-Edged Gradient Source: https://github.com/mazznoer/colorgrad-rs/blob/master/README.md Converts a gradient into a sharp, segmented version. ```rust let g = colorgrad::preset::rainbow().sharp(11, 0.0); ``` -------------------------------- ### Reverse Gradient Direction with inverse() Source: https://context7.com/mazznoer/colorgrad-rs/llms.txt Returns a new gradient instance with the color sequence reversed. ```rust use colorgrad::Gradient; fn main() -> Result<(), Box> { let grad = colorgrad::GradientBuilder::new() .html_colors(&["#fff", "#000"]) // white to black .build::()?; let inverse = grad.inverse(); // now black to white println!("Original at 0.0: {}", grad.at(0.0).to_css_hex()); // #ffffff println!("Inverse at 0.0: {}", inverse.at(0.0).to_css_hex()); // #000000 println!("Original at 1.0: {}", grad.at(1.0).to_css_hex()); // #000000 println!("Inverse at 1.0: {}", inverse.at(1.0).to_css_hex()); // #ffffff // Inverse of preset gradients let viridis = colorgrad::preset::viridis(); let viridis_inv = viridis.inverse(); for t in [0.0, 0.5, 1.0] { println!( "t={}: original={} inverse={}", t, viridis.at(t).to_css_hex(), viridis_inv.at(t).to_css_hex() ); } Ok(()) } ``` -------------------------------- ### Generate Evenly Spaced Colors Source: https://github.com/mazznoer/colorgrad-rs/blob/master/README.md Retrieves a list of colors evenly distributed across the gradient. ```rust use colorgrad::Gradient; let grad = colorgrad::preset::rainbow(); for c in grad.colors(10) { println!("{}", c.to_css_hex()); } ``` ```console #6e40aa #c83dac #ff5375 #ff8c38 #c9d33a #7cf659 #5dea8d #48b8d0 #4775de #6e40aa ``` -------------------------------- ### Convert Gradients to Trait Objects in Rust Source: https://context7.com/mazznoer/colorgrad-rs/llms.txt Use the boxed() method to store different gradient types in a single collection or return them as dynamic types. Requires the Gradient trait to be in scope. ```rust use colorgrad::{Gradient, GradientBuilder, LinearGradient, BlendMode}; fn main() -> Result<(), Box> { // Store different gradient types in one vector let custom: LinearGradient = GradientBuilder::new() .css("#a52a2a, 35%, #ffd700") .mode(BlendMode::Oklab) .build()?; let gradients: Vec> = vec![ custom.sharp(7, 0.0).boxed(), custom.boxed(), colorgrad::preset::magma().boxed(), colorgrad::preset::turbo().boxed(), colorgrad::preset::rainbow().boxed(), ]; // Use all gradients uniformly for (i, grad) in gradients.iter().enumerate() { println!("Gradient {}: midpoint = {}", i, grad.at(0.5).to_css_hex()); } // Conditional gradient selection let use_rainbow = true; let selected: Box = if use_rainbow { colorgrad::preset::rainbow().boxed() } else { colorgrad::preset::sinebow().boxed() }; println!("Selected gradient at 0.25: {}", selected.at(0.25).to_css_hex()); Ok(()) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.