diff --git a/enabler/src/de/schildbach/pte/dto/Style.java b/enabler/src/de/schildbach/pte/dto/Style.java index 92787599..4c036098 100644 --- a/enabler/src/de/schildbach/pte/dto/Style.java +++ b/enabler/src/de/schildbach/pte/dto/Style.java @@ -125,4 +125,16 @@ public class Style implements Serializable { return color & 0xff; } + + public static int deriveForegroundColor(final int backgroundColor) + { + // formula for perceived brightness computation: http://www.w3.org/TR/AERT#color-contrast + final double a = 1 - (0.299 * Style.red(backgroundColor) + 0.587 * Style.green(backgroundColor) + 0.114 * Style.blue(backgroundColor)) / 255; + + // dark colors, white font. Or light colors, black font + if (a >= 0.5) + return WHITE; + else + return BLACK; + } } diff --git a/enabler/test/de/schildbach/pte/dto/StyleTest.java b/enabler/test/de/schildbach/pte/dto/StyleTest.java index 29a1320a..a441cca7 100644 --- a/enabler/test/de/schildbach/pte/dto/StyleTest.java +++ b/enabler/test/de/schildbach/pte/dto/StyleTest.java @@ -32,4 +32,42 @@ public class StyleTest final int color = Style.parseColor("#123456"); assertEquals(color, Style.rgb(Style.red(color), Style.green(color), Style.blue(color))); } + + @Test + public void deriveForegroundColorForLightBackground() + { + final int acacia = Style.rgb(205, 200, 63); + final int lilac = Style.rgb(197, 163, 202); + final int mint = Style.rgb(121, 187, 146); + final int ochre = Style.rgb(223, 176, 57); + final int orange = Style.rgb(222, 139, 83); + final int ranunculus = Style.rgb(242, 201, 49); + final int rose = Style.rgb(223, 154, 177); + final int vinca = Style.rgb(137, 199, 214); + + assertEquals(Style.BLACK, Style.deriveForegroundColor(acacia)); + assertEquals(Style.BLACK, Style.deriveForegroundColor(lilac)); + assertEquals(Style.BLACK, Style.deriveForegroundColor(mint)); + assertEquals(Style.BLACK, Style.deriveForegroundColor(ochre)); + assertEquals(Style.BLACK, Style.deriveForegroundColor(orange)); + assertEquals(Style.BLACK, Style.deriveForegroundColor(ranunculus)); + assertEquals(Style.BLACK, Style.deriveForegroundColor(rose)); + assertEquals(Style.BLACK, Style.deriveForegroundColor(vinca)); + } + + @Test + public void deriveForegroundColorForDarkBackground() + { + final int azure = Style.rgb(33, 110, 180); + final int brown = Style.rgb(141, 101, 56); + final int iris = Style.rgb(103, 50, 142); + final int parme = Style.rgb(187, 77, 152); + final int sapin = Style.rgb(50, 142, 91); + + assertEquals(Style.WHITE, Style.deriveForegroundColor(azure)); + assertEquals(Style.WHITE, Style.deriveForegroundColor(brown)); + assertEquals(Style.WHITE, Style.deriveForegroundColor(iris)); + assertEquals(Style.WHITE, Style.deriveForegroundColor(parme)); + assertEquals(Style.WHITE, Style.deriveForegroundColor(sapin)); + } }