简体   繁体   中英

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". Is it possible to take argb value? (Such as "255255255255" or something) Thank you!

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

Generate Random number between range

A Java color is represented by a 32 bit integer in ARGB format.

That means the highest 8 bit is an alpha value, 255 means full opacity while 0 means transparency. You generate colors with alpha value of 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.

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:

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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