首先,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)
这两种方法基本上和上面创建的第一个方法做同样的事情。