gpt4 book ai didi

java - 如何将Java中的 "Color.rgb"设置为随机?

转载 作者:行者123 更新时间:2023-12-01 19:18:38 25 4
gpt4 key购买 nike

我正在尝试使用 Android studio,我想将随机值传递给 Color.rgb。这是我尝试过的代码

int x  = rand.nextInt(9);
int y = rand.nextInt(9);
int z = rand.nextInt(9);

viewTest.setBackgroundColor(Color.rgb(x,y,z));

编辑:颜色范围在 0 到 255 之间,所以正确的代码是

int x  = rand.nextInt(256);
int y = rand.nextInt(256);
int z = rand.nextInt(256);

viewTest.setBackgroundColor(Color.rgb(x,y,z));

不是最好的解决方案,但它有效感谢jon Skeet提醒我:)

最佳答案

您可以像这样生成随机颜色:

Random rng = new Random();
int red = rng.nextInt(256);
int green = rng.nextInt(256);
int blue = rng.nextInt(256);

viewTest.setBackgroundColor(Color.rgb(red, green, blue));

使用nextInt(256)意味着您将获得一个从0到255的随机int

关于java - 如何将Java中的 "Color.rgb"设置为随机?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59387368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com