[英]Int argb color output strange value
我正在尝试创建使用随机颜色的小型应用程序。
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值? (例如“ 255255255255”之类的东西),谢谢!
试试这个代码,
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值,只需执行逻辑与以截断使十进制数字表示为负的alpha通道位:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.