2017-07-15 57 views
0

我有一种方法将父级的文本和图像色调设置为某种颜色。现在,如果父母和前景的背景(我是设置的色调)相近,则文本将不可读。找到两种颜色之间的对比差异

我该如何检查这两种颜色之间的差异,并将其改变(使其变得更亮或更暗)直至它们变得可读?

下面是我得到了什么至今:

public static void invokeContrastSafety(ViewGroup parent, int tint, boolean shouldPreserveForeground) { 
    Drawable background = parent.getBackground(); 
    if (background instanceof ColorDrawable) { 
     if (isColorDark(((ColorDrawable) background).getColor())) { 
      // Parent background is dark 

      if (isColorDark(tint)) { 
       // Tint (foreground) color is also dark. 
       if (shouldPreserveForeground) { 
        // We can't modify tint color, changing background to make things readable. 


       } else { 
        // Altering foreground to make things readable 

       } 

       invokeInternal(parent, tint); 
      } else { 
       // Everything is readable. Just pass it on. 
       invokeInternal(parent, tint); 
      } 

     } else { 
      // Parent background is light 

      if (!isColorDark(tint)) { 
       if (shouldPreserveForeground) { 

       } else { 

       } 
      } else { 
       invokeInternal(parent, tint); 
      } 
     } 
    } 
} 

private static boolean isColorDark(int color){ 
    double darkness = 1-(0.299* Color.red(color) + 0.587*Color.green(color) + 0.114*Color.blue(color))/255; 
    return darkness >= 0.2; 
} 
+0

看到我的答案希望这会帮助你。 –

+0

可能重复[公式来确定RGB颜色的亮度](https://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color) – geza

回答

0

试试这个工作对我来说。这个函数返回颜色是黑色或者浅色的。

public static boolean isBrightColor(int color) { 
    if (android.R.color.transparent == color) 
     return true; 

    boolean rtnValue = false; 

    int[] rgb = { Color.red(color), Color.green(color), Color.blue(color) }; 

    int brightness = (int) Math.sqrt(rgb[0] * rgb[0] * .241 + rgb[1] 
      * rgb[1] * .691 + rgb[2] * rgb[2] * .068); 

    // Color is Light 
    if (brightness >= 200) { 
     rtnValue = true; 
    } 
    return rtnValue; 
} 

如果需要,您可以在此功能中更改自定义逻辑。

+0

我不好的不加'isColorDark( )'片段中的''功能。我已经知道如何检查。 –

+0

那问题是什么? –

+0

我为逻辑留下了空白区域,使颜色变暗或变浅,直到它在给定的背景颜色上易于阅读。 –

相关问题