Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if color is dark or light in Android

as per title, my question is: Does Android provide any way to analyze/determine if a color (that will be obviously dynamic for the purpose) is light or dark?

like image 725
iGio90 Avatar asked Jun 17 '14 09:06

iGio90


People also ask

How can you tell if a color is dark or light?

Value is the measurement of the amount of black or white mixed into a pure hue. By adding black to the color, the value is made darker, resulting in what is referred to as a “shade.” When white is added to a color, the result is a lighter value, which is referred to as a “tint.”

What is the color of Android?

The hexadecimal color code #a4c639 is a shade of yellow-green. In the RGB color model #a4c639 is comprised of 64.31% red, 77.65% green and 22.35% blue.


2 Answers

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     } } 
like image 156
adboco Avatar answered Oct 18 '22 19:10

adboco


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).

like image 26
Robyer Avatar answered Oct 18 '22 17:10

Robyer