Created
January 24, 2019 19:48
-
-
Save Jthomas54/5c59ec968a7947f2c864a8184bc64e30 to your computer and use it in GitHub Desktop.
Determine contrasting color based on another
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.graphics.Color; | |
public final class ColorsHelper { | |
/** | |
* Contrast constant as defined by W3C for the sRGB color space where white and black are used | |
* as the light and dark colors. | |
* <p> | |
* For more info, see https://www.w3.org/TR/WCAG20/#contrast-ratiodef | |
* </p> | |
*/ | |
private static final double SRGB_CONTRAST_CONSTANT = 0.179; | |
private ColorsHelper() { | |
} | |
/** | |
* Calculates the contrasting color for a given color in the sRGB color space | |
* <p> | |
* For more info, see: {@link ColorsHelper#calculateRelativeLuminance(int)} | |
* </p> | |
* | |
* @param color color to contrast against | |
* @return {@link Color#WHITE} if the color is dark or {@link Color#BLACK} if the color is light | |
*/ | |
public static int calculateContrastingColor(int color) { | |
return calculateRelativeLuminance(color) > SRGB_CONTRAST_CONSTANT ? Color.BLACK : Color.WHITE; | |
} | |
/** | |
* Calculates the relative luminance for a given color in the sRGB color space. | |
* <p> | |
* For more info, see: | |
* </p> | |
* <p> | |
* https://en.wikipedia.org/wiki/SRGB#The_reverse_transformation | |
* <br /> | |
* https://www.w3.org/TR/WCAG20/#relativeluminancedef | |
* </p> | |
* | |
* @param color | |
* @return A value between 0 and 1. A value closer to 0 indicates a dark color, while closer to 1 indicates a light color | |
*/ | |
public static double calculateRelativeLuminance(int color) { | |
//We use the median gamma value of 2.2 | |
double redLuminance = Math.pow(Color.red(color) / 255.0, 2.2); | |
double greenLuminance = Math.pow(Color.green(color) / 255.0, 2.2); | |
double blueLuminance = Math.pow(Color.blue(color) / 255.0, 2.2); | |
return (0.2126 * redLuminance + 0.7152 * greenLuminance + 0.0722 * blueLuminance); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment