java 我怎么能比较java中的颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15262258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:01:44  来源:igfitidea点击:

how could i compare colors in java?

javarandomcolorsrgb

提问by Ryan Maddox

im trying to make a random color generator but i dont want similar colors to show up in the arrayList

我正在尝试制作一个随机颜色生成器,但我不希望在 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;
}

}

I'm really confused please help :)

我真的很困惑请帮忙:)

回答by StarPinkER

Implement a similarTo() method in Color class.

在 Color 类中实现一个 similarTo() 方法。

Then use:

然后使用:

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

To implement the similarTo:

实现similarTo:

Take a look at Color similarity/distance in RGBA color spaceand finding similar colors programatically. A simple approach can be:

看看RGBA 颜色空间中的颜色相似性/距离并以编程方式找到相似的颜色。一个简单的方法可以是:

((r2 - r1)2+ (g2 - g1)2+ (b2 - b1)2)1/2

((r2 - r1) 2+ (g2 - g1) 2+ (b2 - b1) 2) 1/2

And:

和:

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

However, you should find your X according to your imagination of similar.

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

回答by Seikon

I tried this and it worked very well:

我试过这个,效果很好:

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

The getRGBfunction returns an int value with the sum of Red Blue and Green, so we are comparing integers not objects.

getRGB函数返回一个包含红蓝绿总和的 int 值,因此我们比较的是整数而不是对象。