source: josm/trunk/src/org/openstreetmap/josm/tools/ColorHelper.java@ 10369

Last change on this file since 10369 was 9229, checked in by Don-vip, 8 years ago

fix #12262 - NPE

  • Property svn:eol-style set to native
File size: 2.9 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import java.awt.Color;
5import java.util.Locale;
6
7/**
8 * Helper to convert from color to HTML string and back.
9 */
10public final class ColorHelper {
11
12 private ColorHelper() {
13 // Hide default constructor for utils classes
14 }
15
16 /**
17 * Returns the {@code Color} for the given HTML code.
18 * @param html the color code
19 * @return the color
20 */
21 public static Color html2color(String html) {
22 if (!html.isEmpty() && html.charAt(0) == '#')
23 html = html.substring(1);
24 if (html.length() == 3) {
25 return html2color(new String(
26 new char[]{html.charAt(0), html.charAt(0), html.charAt(1), html.charAt(1), html.charAt(2), html.charAt(2)}));
27 }
28 if (html.length() != 6 && html.length() != 8)
29 return null;
30 try {
31 return new Color(
32 Integer.parseInt(html.substring(0, 2), 16),
33 Integer.parseInt(html.substring(2, 4), 16),
34 Integer.parseInt(html.substring(4, 6), 16),
35 html.length() == 8 ? Integer.parseInt(html.substring(6, 8), 16) : 255);
36 } catch (NumberFormatException e) {
37 return null;
38 }
39 }
40
41 private static String int2hex(int i) {
42 String s = Integer.toHexString(i / 16) + Integer.toHexString(i % 16);
43 return s.toUpperCase(Locale.ENGLISH);
44 }
45
46 /**
47 * Returns the HTML color code (6 or 8 digit).
48 * @param col The color to convert
49 * @return the HTML color code (6 or 8 digit)
50 */
51 public static String color2html(Color col) {
52 return color2html(col, true);
53 }
54
55 /**
56 * Returns the HTML color code (6 or 8 digit).
57 * @param col The color to convert
58 * @param withAlpha if {@code true} and alpha value < 255, return 8-digit color code, else always 6-digit
59 * @return the HTML color code (6 or 8 digit)
60 * @since 6655
61 */
62 public static String color2html(Color col, boolean withAlpha) {
63 if (col == null)
64 return null;
65 String code = '#'+int2hex(col.getRed())+int2hex(col.getGreen())+int2hex(col.getBlue());
66 if (withAlpha) {
67 int alpha = col.getAlpha();
68 if (alpha < 255) {
69 code += int2hex(alpha);
70 }
71 }
72 return code;
73 }
74
75 /**
76 * Determines the correct foreground color (black or white) to use for the given background,
77 * so the text will be readable.
78 * @param bg background color
79 * @return {@code Color#BLACK} or {@code Color#WHITE}
80 * @since 9223
81 */
82 public static Color getForegroundColor(Color bg) {
83 // http://stackoverflow.com/a/3943023/2257172
84 return bg == null ? null :
85 (bg.getRed()*0.299 + bg.getGreen()*0.587 + bg.getBlue()*0.114) > 186 ?
86 Color.BLACK : Color.WHITE;
87 }
88}
Note: See TracBrowser for help on using the repository browser.