按HSV/HSB对颜色排序 [英] Sort list of colors by HSV/HSB

查看:81
本文介绍了按HSV/HSB对颜色排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望通过它们的HSV/HSB值对很长的颜色列表进行排序.我想按色相,然后是星期六,然后是光明来对它们进行排序.实际上,我所需要的只是一种方法,可以根据HSV的顺序判断一种颜色是之前"还是之后",因为我只是要在Java中进行compareTo()并使用TreeSet进行排序.在Java中,HSV值都存储为浮点数.

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!

推荐答案

蛮力方式:

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;
    }
}

如果您可以使用Google Guava库,那么一种非常简单,无需考虑的方法是:

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();
    }
}

我想说的只是遍历数组并进行比较(或在Guava中使用字典顺序),但是您可能想更改排序顺序.

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.

这篇关于按HSV/HSB对颜色排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆