colorsNearestHSL function
The n
css colors that are nearest in hsl space to color
.
Example:
final color = "rgb(10, 20, 30)";
for (final c in colorsNearestHSL(color, 3)) {
print(c);
}
Output:
midnightblue
darkslategray
darkslateblue
Implementation
List<String> colorsNearestHSL(String color, [int n = 3]) {
final ps = ColorProperties(color), hue = ps.hueInDegrees;
if (hue == null) throw Exception("Hue not defined for $color.");
final saturation = ps.saturation,
lightness = ps.lightness,
distanceTuple = (String color) {
final ps = ColorProperties(color), h = ps.hueInDegrees;
if (h == null) return null;
final greater = h > hue ? h : hue,
lesser = h < hue ? h : hue,
d = greater - lesser;
final dp = (d > 180 ? 360 - d : d) / 180,
s = ps.saturation - saturation,
l = ps.lightness - lightness;
return (color, dp * dp + s * s + l * l);
},
hueDifferences = [
...Color.colorData.keys.map(distanceTuple).where((d) => d != null)
]..sort((a, b) => _byDistance(a!, b!));
return [...hueDifferences.sublist(0, n).map((t) => _getColor(t!))];
}