问题
I am looking to sort a very long list of colors by their HSV/HSB values. I would like to sort them by Hue, then Sat, then Bright. Really all I need is a way to tell if one color comes "before" or "after" based on that order of HSV since I am just going to make a compareTo() in Java and use a TreeSet to do the ordering. In Java, HSV values are all stored as floats.
I am terrible at algorithms like these so any help would be appreciated!
回答1:
The brute force way:
public final class ColorComparator implements Comparator<Color> {
@Override
public int compare(Color c1, Color c2) {
float[] hsb1 = Color.RGBtoHSB(c1.getRed(), c1.getGreen(), c1.getBlue(), null);
float[] hsb2 = Color.RGBtoHSB(c2.getRed(), c2.getGreen(), c2.getBlue(), null);
if (hsb1[0] < hsb2[0])
return -1;
if (hsb1[0] > hsb2[0])
return 1;
if (hsb1[1] < hsb2[1])
return -1;
if (hsb1[1] > hsb2[1])
return 1;
if (hsb1[2] < hsb2[2])
return -1;
if (hsb1[2] > hsb2[2])
return 1;
return 0;
}
}
A really easy, no-thought way to do it if you can use the Google Guava libraries is:
public final class ColorComparator extends Ordering<Color> {
@Override
public int compare(Color c1, Color c2) {
float[] hsb1 = Color.RGBtoHSB(c1.getRed(), c1.getGreen(), c1.getBlue(), null);
float[] hsb2 = Color.RGBtoHSB(c2.getRed(), c2.getGreen(), c2.getBlue(), null);
return ComparisonChain.start().compare(hsb1[0], hsb2[0]).compare(hsb1[1], hsb2[1])
.compare(hsb1[2], hsb2[2]).result();
}
}
I would say just loop over the arrays and compare them (or use lexicographical ordering in Guava), but you might want to change the sort ordering around.
来源:https://stackoverflow.com/questions/11651781/sort-list-of-colors-by-hsv-hsb