[英]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.