Skip to content

Instantly share code, notes, and snippets.

@kettle11
Created March 6, 2022 15:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kettle11/666edd2645088392582950a8e471c7be to your computer and use it in GitHub Desktop.
Save kettle11/666edd2645088392582950a8e471c7be to your computer and use it in GitHub Desktop.
Code for approximating color names
pub fn get_approximate_color_name(color: koi::Color) -> String {
let considered_exact = 0.1;
let hues = [
(0.0, "Pink"),
((29.0 / 360.), "Red"),
((53.0 / 360.), "Orange"),
((110.0 / 360.), "Yellow"),
((142.0 / 360.0), "Green"),
((195.0 / 360.0), "Cyan"),
((264.0 / 360.0), "Blue"),
((328.0 / 360.0), "Purple"),
(1.0, "Pink"),
];
let (lightness, chroma, hue) = color.get_lightness_chroma_hue();
// println!("LIGHTNESS: {:?}", lightness);
// println!("CHROMA: {:?}", chroma);
// println!("HUE: {:?}", hue);
if lightness > 0.98 && chroma < 0.05 {
return "White".into();
} else if lightness == 0.0 {
return "Black".into();
} else if lightness < 0.24 {
return "Near Black".into();
}
let lightness_descriptor = if lightness > 0.8 {
"Light "
} else if lightness > 0.5 {
""
} else {
"Dark "
};
let chroma_descriptor = if chroma > 0.08 {
""
} else if chroma > 0.05 {
"Grey-ish "
} else {
"Grey "
};
for window in hues.windows(2) {
let left = window[0];
let right = window[1];
let window_size = right.0 - left.0;
if hue >= left.0 && hue <= right.0 {
let distance_to_left = hue - left.0;
let percent_to_left = distance_to_left / window_size;
let (first_name, second_name) = if percent_to_left < considered_exact {
(left.1, "")
} else if percent_to_left > (1.0 - considered_exact) {
(right.1, "")
} else if distance_to_left < 0.5 {
(left.1, right.1)
} else {
(right.1, left.1)
};
return format!(
"{}{}{} {}",
chroma_descriptor, lightness_descriptor, first_name, second_name
);
}
}
// This should be unreachable, but return an empty String.
String::new()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment