【问题标题】:Int argb color output strange valueint argb 颜色输出奇怪的值
【发布时间】:2016-11-06 13:03:57
【问题描述】:

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

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”什么的)谢谢!

【问题讨论】:

  • 想想-11338194代表什么32位整数...然后算出它的4个8位值是什么...
  • @JonSkeet,ghm。字节 b = (byte) color1 不起作用。抱歉,我只是在学习编码
  • 嗯,你必须定义“不起作用”才能有意义......不清楚你的期望。
  • @JonSkeet ,当我尝试转换为字节时,它具有以下值:(color1 = -9003271 并且字节值为-7)
  • 对,但不清楚您的预期是什么或为什么。

标签: java android


【解决方案1】:

试试这个代码,

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

【讨论】:

  • 谢谢!但它不会改变任何东西:(
  • @Dimitry 还在产生负值吗?
  • 是的,它仍在产生负的奇怪值
【解决方案2】:

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

【讨论】:

  • (此示例来自桌面 JavaSE,您可能会发现 Android 中的细微差别。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 2013-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-07
  • 2013-06-14
相关资源
最近更新 更多