简体   繁体   English

int argb颜色输出奇怪的值

[英]Int argb color output strange value

I'm trying to create small app where is using random colors. 我正在尝试创建使用随机颜色的小型应用程序。

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));

But in color1, color2 and color3 saved values such as "-11338194". 但是在color1中,color2和color3保存了诸如“ -11338194”之类的值。 Is it possible to take argb value? 是否可以采用argb值? (Such as "255255255255" or something) Thank you! (例如“ 255255255255”之类的东西),谢谢!

Try this code, 试试这个代码,

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));

Reference for Color.argb() Color.argb()的参考

Generate Random number between range 生成范围之间的随机数

A Java color is represented by a 32 bit integer in ARGB format. Java颜色由ARGB格式的32位整数表示。

That means the highest 8 bit is an alpha value, 255 means full opacity while 0 means transparency. 这表示最高的8位是alpha值,255表示完全不透明,而0表示透明。 You generate colors with alpha value of 255. 您生成的Alpha值为255的颜色。

An Integer is a signed number, its most significant bit tells if it is negative. 整数是一个带符号的数字,它的最高有效位表明它是否为负数。 As you set all the first 8 bits to 1, effectively all Colors will be negative numbers if you print it to the screen. 当您将所有前8位设置为1时,如果将其打印到屏幕上,则所有颜色实际上都是负数。

Example: 例:

 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.

If you only want to see the RGB values, simply do a logical AND to truncate the alpha channel bits which make the decimal numeric representation negative: 如果您只想查看RGB值,只需执行逻辑与以截断使十进制数字表示为负的alpha通道位:

 System.err.println("Color="+(java.awt.Color.RED.getRGB() & 0xffffff));
 gives you 16711680

Alternatively you can get the representation of the color in hex as: 另外,您也可以用十六进制表示颜色:

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

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

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