我必须为ArrayList中的形状提供20种不同颜色的变体。 我不知道该怎么做。 我想把它们添加到数组中,但我不确定它是如何工作的? 有人可以向我解释这一点并暗示/指出我正确的思维方向吗?
答案 0 :(得分:1)
这有点棘手,因为 distinct 和 random 的含义定义不明确。
就计算机而言,新的Color(0xFF000000)和新的Color(0xFF000001)是不同的颜色,但人类将无法识别这两者。它们看起来是一样的:黑色。
他们还需要真正随机吗?如果是这样,那么方法就是创建一个List和循环,直到你创建了所需的颜色数,同时检查新创建的随机颜色是否与目前生成的所有颜色完全不同,以便人眼可以辨别:
Random generator = new Random();
List<Color> colors = new ArrayList<>();
while (list.size() < numberDesired) {
Color randomColor = new Color(generator.nextInt(), false);
// check each color in list against list
boolean isDisinct = true;
for (Color existingColor : colors) {
isDistinct &= isDistinct(existingColor, randomColor);
}
if (isDistintc) {
colors.add(randomColor);
}
}
return colors;
方法isDistinct(颜色,颜色)可以通过棘手来实现,因为它需要考虑人眼属性。
它实际上更容易预定义20种手工挑选的颜色,并根据需要采取尽可能多的颜色。颜色不是真正随机的,但对于大多数目的而言,这已经足够好了:
static List<Color> COLORS = new ArrayList<>();
static
COLORS.add(Color.WHITE);
COLORS.add(Color.RED);
... // 18 more colors
}
public List<Color> getColors(int count) {
List<Color> result = new ArrayList<>(count);
for (int i=0; i<count; ++i)
result.add(COLORS.get(i));
return result;
}
答案 1 :(得分:0)
创建颜色列表,然后将其设置为您的形状
for(Shape myShape : myShapeList){
int randomColor = (int)(Math.random()*myColorList.size());
myShape.setColor(myColorList.get(randomColor));
}
答案 2 :(得分:0)
要制作随机颜色,您需要为颜色的每个红色,绿色和蓝色组件提供随机数。在Color
类中,您可以为这三个组件中的每一个指定0到255之间的值,但这样可以为您提供如此精细的颜色粒度,最终可能会出现一些与大多数人看起来相同的颜色,但实际上是不同的。因此,您可能决定将每个数字限制为5的倍数,例如,在0到255的范围内。这将为每个通道提供52个不同的值,总共约140 000种可能的颜色。
所以你可以有这样的方法,给你你的颜色。
public Color makeRandomColor() {
int red = 5 * (int)(Math.random() * 52);
int green = 5 * (int)(Math.random() * 52);
int blue = 5 * (int)(Math.random() * 52);
return new Color(red, green, blue);
}
此处,Math.random()
为您提供小于1的浮点值。将它乘以52使得它小于52. (int)
强制转换为向下舍入,因此它最终成为0到51之间的整数。最后,乘以5将其置于0到255的范围内,这是你想要什么。这种方式可以保证每个组件都是5的倍数,这样就不会得到距离太近的颜色。
下一个技巧是为要应用颜色的每个形状调用此方法。我不太确定你在Shape
类中使用哪种方法来应用颜色,但如果你有setColor
方法,那么你的代码看起来就像这样。
for(Shape eachShape : shapeList) {
eachShape.setColor(makeRandomColor());
}
请试验一下。例如,您可能会发现最终会出现太多的深色 - 暗黑色和深褐色,这些都不会给您带来您想要的视觉效果。如果证明是这种情况,你可以在makeRandomColor()
方法中加入一些奇特的数学,这样每个组件产生的数字更可能比较低的数字。这会给你更明亮的颜色。
但我希望我在这里给你的东西可以帮助你开始。