Created
August 24, 2015 14:55
-
-
Save tanhauhau/23ab6b56b061fd1c1a17 to your computer and use it in GitHub Desktop.
White or black text based on background colour
This file contains hidden or 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; | |
/** | |
* Created by lhtan on 24/8/15. | |
* Based on How to decide font color in white or black depending on background color? | |
* http://stackoverflow.com/questions/3942878/how-to-decide-font-color-in-white-or-black-depending-on-background-color | |
*/ | |
public class ColorUtil { | |
/** | |
* compute text color, either white or black based on colorString | |
* @param colorString color string in format #XXXXXX | |
* @return int Color.WHITE or Color.BLACK based on the colorString | |
*/ | |
public static int computeTextColorFromBackgroundColor1(String colorString){ | |
long color = Long.parseLong(colorString.substring(1), 16); | |
if (colorString.length() == 7) { | |
final int r = (int)((color & 0x0000000000ff0000) >> 16); | |
final int g = (int)((color & 0x000000000000ff00) >> 8); | |
final int b = (int)(color & 0x00000000000000ff); | |
if ((r*0.299 + g*0.587 + b*0.114) > 186){ | |
return Color.BLACK; | |
}else{ | |
return Color.WHITE; | |
} | |
} else if (colorString.length() != 9) { | |
throw new IllegalArgumentException("Unknown color"); | |
} | |
return Color.WHITE; | |
} | |
public static int computeTextColorFromBackgroundColor2(String colorString){ | |
long color = Long.parseLong(colorString.substring(1), 16); | |
if (colorString.length() == 7) { | |
final int r = (int)((color & 0x0000000000ff0000) >> 16); | |
final int g = (int)((color & 0x000000000000ff00) >> 8); | |
final int b = (int)(color & 0x00000000000000ff); | |
double rd = gammaCorrect(r); | |
double gd = gammaCorrect(g); | |
double bd = gammaCorrect(b); | |
double luminance = 0.2126 * rd + 0.7152 * gd + 0.0722 * bd; | |
if(luminance > 0.179){ | |
return Color.BLACK; | |
}else { | |
return Color.WHITE; | |
} | |
} else if (colorString.length() != 9) { | |
throw new IllegalArgumentException("Unknown color"); | |
} | |
return Color.WHITE; | |
} | |
private static double gammaCorrect(int value){ | |
double c = value/255.0; | |
if (c <= 0.03928){ | |
c = c/12.92; | |
} else { | |
c = Math.pow(((c+0.055)/1.055), 2.4); | |
} | |
return c; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment