繁体   English   中英

如何将 Java 中的“Color.rgb”设置为随机?

[英]how to set the "Color.rgb" in Java to random?

我正在试验 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(255);
int y  = rand.nextInt(255);
int z  = rand.nextInt(255);

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(266)意味着您将获得一个从 0 到 255 的随机int

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM