pub fn gradient_filled_segment(filled_width: usize, ch: char) -> StringExpand description
Creates a gradient-colored text segment for terminal display.
This function generates a string containing a gradient-colored sequence of characters using ANSI escape codes. Each character is colored using linear interpolation between Charm’s default gradient colors, creating a smooth color transition from left to right. This is commonly used for progress bars, loading indicators, and other visual elements in terminal user interfaces.
§Arguments
filled_width- The number of characters to include in the gradient segment. If 0, returns an empty string.ch- The character to repeat for each position in the gradient (commonly ‘█’, ‘▓’, etc.)
§Returns
A String containing the gradient-colored characters with embedded ANSI escape sequences.
Each character includes both the foreground color code and a reset sequence.
§Performance Notes
This function pre-allocates string capacity and manually constructs ANSI sequences to avoid the overhead of format macros and style library allocations. It’s optimized for repeated use in animation loops and real-time rendering.
§Examples
use bubbletea_rs::gradient::gradient_filled_segment;
// Create a 10-character gradient progress bar
let progress = gradient_filled_segment(10, '█');
println!("{}", progress);
// Create a loading spinner segment
let spinner = gradient_filled_segment(5, '▓');
print!("Loading: {}\r", spinner);
// Empty width returns empty string
let empty = gradient_filled_segment(0, '█');
assert_eq!(empty, "");§ANSI Escape Sequence Format
Each character in the output follows the pattern:
\x1b[38;2;r;g;bm{char}\x1b[0m
Where:
\x1b[38;2;r;g;bmsets the foreground color to RGB(r,g,b){char}is the specified character\x1b[0mresets all formatting
§See Also
gradient_filled_segment_with_buffer- Buffer-reusing variant for better performancecharm_default_gradient- The gradient colors used by this functionlerp_rgb- The color interpolation function used internally