【问题标题】:Automatically determine optimal fontcolor by backgroundcolor [duplicate]通过背景颜色自动确定最佳字体颜色 [重复]
【发布时间】:2012-02-03 05:12:31
【问题描述】:

可能重复:
given a background color, how to get a foreground color that make it readable on that background color?

我想知道,是否有任何算法可以通过背景颜色确定最佳字体颜色以提高可读性。

例如: 我创建了一个带有动态文本和颜色的图标。如果颜色有点暗,我希望它设置字体颜色为白色,如果它相当亮,我希望它是黑色(甚至可能是灰色)。

  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;
  }

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

谢谢, 梅内

【问题讨论】:

    标签: java swing fonts colors


    【解决方案1】:

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

    这就是我们所做的:

    int red = 0;
    int green = 0;
    int blue = 0;
    
    if ( backgroundColor.red + backgroundColor.green + backgroundColor.blue < 383 ) {
        red = 255;
        green = 255;
        blue = 255;
    }
    

    然后我们使用redgreenblue 值来创建一个新的Color 对象。

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

    【讨论】:

    • 感谢您分享您的想法。我会试试看。对我来说可能也足够了。
    • rgb(191,87,218) 是一种相当深的紫色 OSX 用于列表选择背景色(他们使用白色作为文本前景色。)191+87+218=496,所以这个算法会确定它是“轻的”。我的另一个解决方案是转换为 HSB,然后使用 B 值作为截止值,但在同一个示例中失败了。
    猜你喜欢
    • 1970-01-01
    • 2016-04-03
    • 2020-12-13
    • 2014-02-12
    • 1970-01-01
    • 2019-12-22
    • 2013-06-03
    • 1970-01-01
    相关资源
    最近更新 更多