Java Int argb颜色输出奇怪值

Java Int argb颜色输出奇怪值,java,android,Java,Android,我正在尝试创建一个使用随机颜色的小应用程序 Random rnd = new Random(); int color1 = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)); int color2 = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)); int color

我正在尝试创建一个使用随机颜色的小应用程序

Random rnd = new Random();
        int color1 = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
        int color2 = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
        int color3 = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
但在color1中,color2和color3保存了“-11338194”等值。可以取argb值吗?(比如“255255”之类的)谢谢

试试这个代码

Random rnd = new Random();
        int color1 = Color.argb(255, rnd.nextInt(256 - 0), rnd.nextInt(256 - 0), rnd.nextInt(256 - 0));
        int color2 = Color.argb(255, rnd.nextInt(256 - 0), rnd.nextInt(256 - 0), rnd.nextInt(256 - 0));
        int color3 = Color.argb(255, rnd.nextInt(256 - 0), rnd.nextInt(256 - 0), rnd.nextInt(256 - 0));


Java颜色由ARGB格式的32位整数表示

这意味着最高的8位是alpha值,255表示完全不透明度,而0表示透明度。生成alpha值为255的颜色

整数是一个有符号的数字,它的最高有效位表示它是否为负数。当您将所有前8位设置为1时,如果您将其打印到屏幕上,所有颜色实际上都将是负数

例如:

 System.err.println("Color="+new java.awt.Color(0,0,255,0).getRGB());
 gives 255 as you expected - note that this is a fully transparent blue

 System.err.println("Color="+java.awt.Color.RED.getRGB());
 gives -65536, as the alpha channel value is 255 making the int negative.
如果您只想查看RGB值,只需执行逻辑AND操作,以截断使十进制数字表示为负数的字母通道位:

 System.err.println("Color="+(java.awt.Color.RED.getRGB() & 0xffffff));
 gives you 16711680
或者,您可以使用十六进制表示颜色,如下所示:

System.err.println("Color="+String.format("%X",java.awt.Color.RED.getRGB() & 0xffffff));
which gives FF0000

考虑一下-11338194表示的32位整数。。。然后算出它的4个8位值是什么…@JonSkeet,ghm。字节b=(字节)颜色1不工作。对不起,我只是在学习如何编码你必须定义“不工作”才能理解。。。“不清楚您期望的是什么。@JonSkeet,当我试图转换成字节is时,它的值是:(color1=-9003271,字节值是-7)正确的,但不清楚您期望的是什么或为什么。谢谢!但它并没有改变任何东西:(@Dimitry仍然在生成负值?是的,它仍然在生成奇怪的负值(这个例子来自桌面JavaSE,您可能会发现Android中的细微差别。)