【问题标题】:how could i compare colors in java?我如何在java中比较颜色?
【发布时间】:2013-02-22 02:58:44
【问题描述】:

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

}

我真的很困惑,请帮忙:)

【问题讨论】:

    标签: java random colors rgb


    【解决方案1】:

    我试过了,效果很好:

    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 函数返回一个带有红色蓝色和绿色之和的 int 值,因此我们比较的是整数而不是对象。

    【讨论】:

    • 这可能是正确的,但它没有回答问题,即要求找到相似的颜色,而不仅仅是相同的颜色。
    【解决方案2】:

    在 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:

    看看Color similarity/distance in RGBA color spacefinding similar colors programatically。一个简单的方法可以是:

    ((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颜色匹配差异的问题。
    猜你喜欢
    • 2015-11-11
    • 2012-09-05
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多