Check if color is dark or light in Android
Solution 1:
Android doesn't provide it, you can implement a method to determine this. Here a method to do that:
public boolean isColorDark(int color){
double darkness = 1-(0.299*Color.red(color) + 0.587*Color.green(color) + 0.114*Color.blue(color))/255;
if(darkness<0.5){
return false; // It's a light color
}else{
return true; // It's a dark color
}
}
Solution 2:
If you use support library v4 (or AndroidX), you can use ColorUtils.calculateLuminance(color)
, which returns luminance of color as float between 0.0
and 1.0
.
So you can do something like:
boolean isDark(int color) {
return ColorUtils.calculateLuminance(color) < 0.5;
}
See:
- Support library v4: https://developer.android.com/reference/android/support/v4/graphics/ColorUtils.html#calculateLuminance(int)
- AndroidX: https://developer.android.com/reference/androidx/core/graphics/ColorUtils#calculateLuminance(int)
Note since Android API 24 there is also method: Color.luminance(color)
.
Solution 3:
public float getLightness(int color) {
int red = Color.red(color);
int green = Color.green(color);
int blue = Color.blue(color);
float hsl[] = new float[3];
ColorUtils.RGBToHSL(red, green, blue, hsl);
return hsl[2];
}
One could easily use the ColorUtils to check the lightness of a color.
if (getLightness(color) < 0.5f ){
// This color is too dark!
}