如何在java中将rgb颜色转换为int

新手上路,请多包涵

Paint.setColor 需要一个整数。但是我有一个 Color 对象。我在 Java 中没有看到 color.getIntValue() ?那我该怎么做呢?我想要的是像

public Something myMethod(Color rgb){
    myPaint.setColor(rgb.getIntValue());
    ...
}

更正: android.graphics.Color; 我认为将 android 作为标签之一就足够了。但显然不是。

原文由 Cote Mounyo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 956
1 个回答

首先,android.graphics.Color 是一个仅由静态方法组成的类。您如何以及为何创建新的 android.graphics.Color 对象? (这完全没用,对象本身不存储任何数据)

但无论如何……我会假设你使用一些实际存储数据的对象……

一个整数由 4 个字节组成(在 java 中)。查看标准 java Color 对象中的函数 getRGB(),我们可以看到 java 将每种颜色按 ARGB(Alpha-Red-Green-Blue)的顺序映射到整数的一个字节。我们可以使用自定义方法复制此行为,如下所示:

 public int getIntFromColor(int Red, int Green, int Blue){
    Red = (Red << 16) & 0x00FF0000; //Shift red 16-bits and mask out other stuff
    Green = (Green << 8) & 0x0000FF00; //Shift Green 8-bits and mask out other stuff
    Blue = Blue & 0x000000FF; //Mask out anything not blue.

    return 0xFF000000 | Red | Green | Blue; //0xFF000000 for 100% Alpha. Bitwise OR everything together.
}

这假设您可以以某种方式检索单独的红色、绿色和蓝色分量,并且您为这些颜色传入的所有值都是 0-255。

如果您的 RGB 值采用 0 到 1 之间的浮点百分比形式,请考虑以下方法:

 public int getIntFromColor(float Red, float Green, float Blue){
    int R = Math.round(255 * Red);
    int G = Math.round(255 * Green);
    int B = Math.round(255 * Blue);

    R = (R << 16) & 0x00FF0000;
    G = (G << 8) & 0x0000FF00;
    B = B & 0x000000FF;

    return 0xFF000000 | R | G | B;
}

正如其他人所说,如果您使用的是标准 java 对象,只需使用 getRGB();

如果您决定正确使用 android 颜色类,您还可以执行以下操作:

 int RGB = android.graphics.Color.argb(255, Red, Green, Blue); //Where Red, Green, Blue are the RGB components. The number 255 is for 100% Alpha

或者

int RGB = android.graphics.Color.rgb(Red, Green, Blue); //Where Red, Green, Blue are the RGB components.

正如其他人所说…(第二个函数假设 100% alpha)

这两种方法基本上与上面创建的第一种方法做同样的事情。

原文由 initramfs 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题