“颜色”通常是指 24 位 RGB 颜色:1 个字节(8 位)用于红色、绿色、蓝色。也就是说,每个通道的值都在 0-255 之间,或者十六进制显示为 0x00 到 0xff。
白色表示所有通道已满:#FFFFFF,黑色表示所有通道已关闭:#000000。显然,颜色越浅意味着通道中的值越高,颜色越深意味着通道中的值越低。
您如何选择算法取决于您,简单的是:
//pseudo-code
if (red + green + blue <= (0xff * 3) / 2) //half-down, half-up
fontcolor = white;
else
fontcolor = black;
编辑:提问者要求更完整的例子,所以他/她可以有更好的开始,所以这里是:
public static void main(String[] args) throws IOException {
String value =
// new Scanner(System.in).nextLine(); //from input
"#112233"; //from constant
int red = Integer.parseInt(value.substring(1, 1 + 2), 16);
int green = Integer.parseInt(value.substring(3, 3 + 2), 16);
int blue = Integer.parseInt(value.substring(5, 5 + 2), 16);
System.out.println("red = " + Integer.toHexString(red)
+ ", green = " + Integer.toHexString(green)
+ ", blue = " + Integer.toHexString(blue));
if (red + green + blue <= 0xff * 3 / 2)
System.out.println("using white color #ffffff");
else
System.out.println("using black color #000000");
String colorBackToString = "#" + Integer.toHexString(red) +
Integer.toHexString(green) +
Integer.toHexString(blue);
System.out.println("color was " + colorBackToString);
}
它产生输出:
红色 = 11,绿色 = 22,蓝色 = 33
使用白色#ffffff
颜色是#112233
并展示了将#aabbcc 格式的颜色拆分为 rgb 通道、稍后加入它们(如果需要)等的技术。