Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Automatic text color selection using relative luminance.
public class ColorUtils {
private static final double LM_RED_COEFFICIENT = 0.2126;
private static final double LM_GREEN_COEFFICIENT = 0.7152;
private static final double LM_BLUE_COEFFICIENT = 0.0722;
public static int calculateRelativeLuminance(int color) {
int red = (int) (Color.red(color) * LM_RED_COEFFICIENT);
int green = (int) (Color.green(color) * LM_GREEN_COEFFICIENT);
int blue = (int) (Color.blue(color) * LM_BLUE_COEFFICIENT);
return red + green + blue;
}
}
Resources res = getResources();
int light = res.getColorStateList(R.color.primary_text_holo_light);
int dark = res.getColorStateList(R.color.primary_text_holo_dark);
double luminance = ColorUtils.calculateRelativeLuminance(myColor)/255.0;
if (luminance > 0.60) {
ribbon.setTextColor(light);
} else {
ribbon.setTextColor(dark);
}
@tasomaniac
Copy link

tasomaniac commented Jun 16, 2014

You can also write a Utility function to do this or a CustomTextView that automatically change its color based on relativeLuminance. That would be cool.

@vimalrajpara2006
Copy link

vimalrajpara2006 commented Jun 24, 2014

It seems foolish question but can you pls eloborate.

1 R.color.primary_text_holo_light & R.color.primary_text_holo_dark will remain static ?
2 In myColor variable we need to pass int type color but is it from res directory ?
3 Is there any relation between R.color.primary_text_holo_light, R.color.primary_text_holo_dark & myColor ?

An example will be helpful for more understanding :)

@Sottti
Copy link

Sottti commented Jul 4, 2014

Interesting. I guess this has sense in scenarios where the background color is dynamic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment