本文介绍了我怎么能比较java中的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我想让一个随机颜色生成器,但我不想要类似的颜色显示在arrayList im trying to make a random color generator but i dont want similar colors to show up in the arrayListpublic 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;}} :)推荐答案在Color类中实现similarTo()方法。Implement a similarTo() method in Color class.然后使用: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:To implement the similarTo:查看 RGBA颜色空间中的颜色相似性/距离并按程序查找相似颜色。一个简单的方法可以是:Take a look at Color similarity/distance in RGBA color space and finding similar colors programatically. A simple approach can be:((r2-r1) 2 +(g2 - g1) 2 (b2-b1) 2 ) 1/2 ((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的相似。However, you should find your X according to your imagination of similar. 这篇关于我怎么能比较java中的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-25 00:26