Skip to main content

Crate nearest_color

Crate nearest_color 

Source
Expand description

§nearest-color — find the nearest color from a palette

Given a target color and a list of available colors, find the closest one by Euclidean distance in RGB space — useful for snapping arbitrary colors to a theme palette, naming colors, or quantizing. Colors may be given as hex (#f00, #ff0000), rgb(…) strings, or the 17 standard CSS color names.

A faithful Rust port of the nearest-color npm package. Zero dependencies.

use nearest_color::Matcher;

let palette = Matcher::from_named(&[
    ("maroon", "#800"),
    ("pale blue", "#def"),
    ("white", "fff"),
]).unwrap();

let m = palette.nearest("#f00").unwrap().unwrap();
assert_eq!(m.name.as_deref(), Some("maroon"));
assert_eq!(m.value, "#800");
assert_eq!(m.rgb, nearest_color::Rgb { r: 136, g: 0, b: 0 });

With an unnamed palette (or the built-in rainbow defaults), the match’s name is None and value holds the nearest color’s source string:

use nearest_color::nearest_color;
assert_eq!(nearest_color("#f88").unwrap().value, "#f80");

Structs§

ColorMatch
The result of a nearest-color match.
InvalidColor
The error returned for an unparseable color string.
Matcher
A reusable nearest-color matcher built from a fixed palette.
Rgb
An RGB color. Components are stored as i32 to faithfully carry through out-of-range rgb() inputs (the reference does not clamp).

Constants§

STANDARD_COLORS
The 17 standard CSS color names recognized by parse_color.

Functions§

default_matcher
A matcher over the built-in default palette (the rainbow colors, unnamed).
nearest_color
Find the nearest of the built-in default (rainbow) colors to needle.
parse_color
Parse a color string into Rgb.