Android / Java: determining if text color will mix with background?

I present the functionality of "tagging" in my application, and one way to display tags is to set the text to the color that the user selected for each. My application has three themes with backgrounds that are white, black and brown (for example, they may change / grow in the future). I want to be able to display the tag in its native color if it easily contrasts with the background and just uses the default text color for each theme otherwise.

I wrote a helper function that helps me determine if the text will be masked, but it is not 100% correct (I want it to determine whether the colors will be masked based on all three hsv components, and right now the saturation comparison is invalid). The code is below.

public static boolean colorWillBeMasked(int color, Application app){ float[] hsv = new float[3]; Color.colorToHSV(color, hsv); //note 0, black 1, white 2 int theme = app.api.getThemeView(); System.out.println("h=" +hsv[0]+ ", s=" +hsv[1]+ ", v=" +hsv[2]+", theme="+theme); if(android.R.color.transparent == color) return true; // color is dark if(hsv[2] <= .2){ if(theme == 1) return true; } // color is light else if(hsv[2] >= .8) { if(theme == 2) return true; } return false; } 

When this function is called with blue, red, transparent, black, yellow and green, the outputs are as follows (respectively):

  • h = 0.0, s = 1.0, v = 1.0, theme = 1
  • h = 229.41177, s = 1.0, v = 1.0, theme = 1
  • h = 267.6923, s = 1.0, v = 0.050980393, theme = 1
  • h = 0.0, s = 0.0, v = 0.0, theme = 1
  • h = 59.52941, s = 1.0, v = 1.0, theme = 1
  • h = 111.29411, s = 1.0, v = 1.0, theme = 1

My question is: based on hue, saturation and value, how can you determine whether text colored in a certain way will appear on a white background or on a black background or if it will be masked? Please take my algorithm and improve it or help me create a new one.

Thanks in advance.

+6
source share
1 answer

The solution I came across:

I ended up using the algorithm found on this blog to override my function as follows; Then I adjusted the brightness at each end. Hope this helps someone.

 public static boolean colorWillBeMasked(int color, Application app){ if(android.R.color.transparent == color) return true; 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); System.out.println("COLOR: " + color + ", BRIGHT: " + brightness); //note 0,black 1,classic 2 int theme = app.api.getThemeView(); // color is dark if(brightness <= 40){ if(theme == 1) return true; } // color is light else if (brightness >= 215){ if(theme == 2) return true; } return false; } 
+3
source

Source: https://habr.com/ru/post/899401/


All Articles