Check if color is dark or light in Android
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!
}
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
}
}
In case one would like to find out whether background color is light or dark to determine what color to use for text drawn on top of it (white or black) – calculating luminance won't provide you correct value in all the cases.
Consider you have background color: #7f6fad
.
If you check its luminance (via ColorUtils#calculateLuminance
) you'll get: 0.1889803503770053
, which is below 0.5
and therefore should be considered as dark following that logic.
But if you follow WCAG you'll see that for general text contrast should be at least 4.5:1.
ColorUtils has method calculateContrast
which will give the following results:
- For white text color:
4.393666669010922
- For black text color:
4.779607007540106
One can see that contrast which white text gives is not enough, while black is good. Therefore if you'd like to check what color to draw on top of some generic background color it is better to check contrasts instead:
@ColorInt
fun getContrastColor(@ColorInt color: Int): Int {
val whiteContrast = ColorUtils.calculateContrast(Color.WHITE, color)
val blackContrast = ColorUtils.calculateContrast(Color.BLACK, color)
return if (whiteContrast > blackContrast) Color.WHITE else Color.BLACK
}
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)
.