如何在Java中比较颜色?

8

我正在尝试制作一个随机颜色生成器,但不希望类似的颜色出现在ArrayList中。

public class RandomColorGen {

public static Color RandColor() {
    Random rand = new Random();
    float r = rand.nextFloat();
    float g = rand.nextFloat();
    float b = rand.nextFloat();
    Color c = new Color(r, g, b, 1);
    return c;

}

public static ArrayList<Color> ColorList(int numOfColors) {
    ArrayList<Color> colorList = new ArrayList<Color>();
    for (int i = 0; i < numOfColors; i++) {
        Color c = RandColor();
        if(similarcolors){
            dont add
        }
        colorList.add(c);

    }
    return colorList;
}

}

我很困惑,请帮忙解决 :)
2个回答

14
在Color类中实现similarTo()方法。
然后使用:
public static ArrayList<Color> ColorList(int numOfColors) {
    ArrayList<Color> colorList = new ArrayList<Color>();
    for (int i = 0; i < numOfColors; i++) {
        Color c = RandColor();
        boolean similarFound = false;
        for(Color color : colorList){
            if(color.similarTo(c)){
                 similarFound = true;
                 break;
            }
        }
        if(!similarFound){
            colorList.add(c);
        } 

    }
    return colorList;
}

要实现similarTo功能:
请参考RGBA颜色空间中的颜色相似度/距离程序化查找相似颜色。一个简单的方法是:
((r2 - r1)2 + (g2 - g1)2 + (b2 - b1)2)1/2 以及:
boolean similarTo(Color c){
    double distance = (c.r - this.r)*(c.r - this.r) + (c.g - this.g)*(c.g - this.g) + (c.b - this.b)*(c.b - this.b)
    if(distance > X){
        return true;
    }else{
        return false;
    }
}

然而,根据你对相似物的想象,你应该找到自己的X。

这可以用来解决Robot.getPixelColor(int x, int y)在OSX上颜色匹配不一致的问题。 - Charles Mosndup

5
我尝试过这个方法,效果非常好:
Color c1 = Color.WHITE;
Color c2 = new Color(255,255,255);

if(c1.getRGB() == c2.getRGB()) 
    System.out.println("true");
else
    System.out.println("false");
}
getRGB函数返回一个整数值,该值是红色、蓝色和绿色的总和,因此我们比较的是整数而不是对象。

7
这个说法可能是正确的,但它没有回答问题,问题要求找到类似的颜色,而不仅仅是完全相同的颜色。 - Synchro

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接