This solution uses the java.awt.Color
class to derive the brightness value of the colour and use that to determine which background colour should be used.
edit: This solution is differs from some of the other solutions because the other solutions will consider some bright colours to be dark eg. primary red (#FF0000). Whereas this solution, will consider primary red to be one of the brightest colours you can have. I suppose it depends on your preferences. Do you want to read red on black or red on white?
String fontColor = "#0cf356";
// remove hash character from string
String rawFontColor = fontColor.substring(1,fontColor.length());
// convert hex string to int
int rgb = Integer.parseInt(rawFontColor, 16);
Color c = new Color(rgb);
float[] hsb = Color.RGBtoHSB(c.getRed(), c.getGreen(), c.getBlue(), null);
float brightness = hsb[2];
if (brightness < 0.5) {
// use a bright background
} else {
// use a dark background
}
HSB stands for Hue, Saturation, Brightness -- brightness is also known as luminosity. With the Color class values are between 1 and 0. Ergo, 0.5 brightness is the the halfway point between the brightest colours and the darkest colours).
The interplay between hue, saturation and brightness are a little more complex than red, blue and green. Use this tool experiment with different colours and find the relationships between RGB and HSB
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…