Skip to content

Instantly share code, notes, and snippets.

@amilcar-sr
Last active December 1, 2022 16:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save amilcar-sr/9d7a1029fa1f4ba7c1bb479102386162 to your computer and use it in GitHub Desktop.
Save amilcar-sr/9d7a1029fa1f4ba7c1bb479102386162 to your computer and use it in GitHub Desktop.
ColorUtils class containing method to parse hexadecimal colors to int and method that determines whether a color is dark or light.
//------------------------------- Class -------------------------------------------
import android.graphics.Color;
import android.support.annotation.NonNull;
public class ColorUtils {
/**
* Luma Coefficients
*
* @see <a href="https://en.wikipedia.org/wiki/Luma_(video)</a> for further information about these values
*/
private static final double RED_LUMA = 0.299;
private static final double GREEN_LUMA = 0.587;
private static final double BLUE_LUMA = 0.587;
private static final double DARKNESS_RESISTANCE = 0.5;
/**
* Method that checks whether a color is light or dark depending on its luma value
*
* @param hexColor Color we want to check
* @return true if the color is closer to dark, false otherwise
*/
public static boolean isDarkColor(String hexColor) {
int color = getIntColor(hexColor);
double luma = 1 - (RED_LUMA * Color.red(color) + GREEN_LUMA * Color.green(color) + BLUE_LUMA * Color.blue(color)) / 255;
return luma >= DARKNESS_RESISTANCE;
}
/**
* Returns int value of hex color
*
* @see <a href="https://developer.android.com/reference/android/graphics/Color.html#parseColor(java.lang.String)"</a> for valid hex color formats.
* @param hexColor Hexadecimal color
* @return int color
*/
public static int getIntColor(@NonNull String hexColor) {
return Color.parseColor((hexColor.contains("#") ? "#" : "") + hexColor);
}
}
//------------------------------- Usage Example 1 -------------------------------------------
if(ColorUtils.isDarkColor("#C3C3C3" /* Hypothetical feed color */)){
view.setBackgroundColor(R.color.light_background_color);
} else{
view.setBackgroundColor(R.color.dark_background_color);
}
//------------------------------- Usage Example 2 -------------------------------------------
someView.setBackgroundColor(ColorUtils.getIntColor("#524686" /* Hypothetical feed color */));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment