通过backgroundcolor自动确定最佳fontcolor

cru*_*sam 6 java fonts swing colors

可能重复:
给定背景颜色,如何获得使其在背景颜色上可读的前景色?

我想知道,如果有任何算法可以通过其背景颜色确定最佳字体颜色的可读性.

例如:我创建了一个包含动态文本和颜色的图标.如果颜色有点暗,我希望它将字体颜色设置为白色,如果颜色相当明亮,我希望它是黑色(或者甚至是灰色).

  public DynamicIcon( String iconText, Color backgroundColor )
  {
    this.iconText = iconText;
    this.backgroundColor = backgroundColor;

    this.fontColor = determineFontColor( backgroundColor );
  }

  //This is what I need (Pseudocode):
  private fontColor determineFontColor( Color backgroundColor )
  {
    if( backgroundColor == bright )
      return Color.BLACK;
    if( backgroundColor == dark )
      return Color.WHITE;
    //If possible:
    if( backgroundColor == somethingInBetween )
      return Color.GRAYISH;
  }
Run Code Online (Sandbox Code Playgroud)

不幸的是,我没有找到任何类似的算法,尽管我很确定,它已经存在了.有人有什么想法吗?

谢谢,ymene

Mar*_*ato 1

我们必须在我们的系统上做类似的事情:根据背景,我们将字体着色为黑色或白色。我们找到的解决方案并不完美,在极少数情况下会选择错误的颜色,但我们对此非常满意。

这就是我们所做的:

int red = 0;
int green = 0;
int blue = 0;

if ( backgroundColor.red + backgroundColor.green + backgroundColor.blue < 383 ) {
    red = 255;
    green = 255;
    blue = 255;
}
Run Code Online (Sandbox Code Playgroud)

然后我们使用red,greenblue值来创建一个新Color对象。

神奇数字 383 是 ( 255 + 255 + 255 ) / 2 的结果