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

Last change on this file since 6682 was 6655, checked in by Don-vip, 10 years ago

fix #9535 - handling of alpha values in HTML color codes (used in preferences)

  • Property svn:eol-style set to native
File size: 2.1 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import java.awt.Color;
5
6/**
7 * Helper to convert from color to html string and back
8 */
9public final class ColorHelper {
10
11 private ColorHelper() {
12 // Hide default constructor for utils classes
13 }
14
15 /**
16 * Returns the {@code Color} for the given HTML code.
17 * @param html the color code
18 * @return the color
19 */
20 public static Color html2color(String html) {
21 if (html.length() > 0 && html.charAt(0) == '#')
22 html = html.substring(1);
23 if (html.length() != 6 && html.length() != 8)
24 return null;
25 try {
26 return new Color(
27 Integer.parseInt(html.substring(0,2),16),
28 Integer.parseInt(html.substring(2,4),16),
29 Integer.parseInt(html.substring(4,6),16),
30 (html.length() == 8 ? Integer.parseInt(html.substring(6,8),16) : 255));
31 } catch (NumberFormatException e) {
32 return null;
33 }
34 }
35
36 private static String int2hex(int i) {
37 String s = Integer.toHexString(i / 16) + Integer.toHexString(i % 16);
38 return s.toUpperCase();
39 }
40
41 /**
42 * Returns the HTML color code (6 or 8 digit).
43 * @param col The color to convert
44 * @return the HTML color code (6 or 8 digit)
45 */
46 public static String color2html(Color col) {
47 return color2html(col, true);
48 }
49
50 /**
51 * Returns the HTML color code (6 or 8 digit).
52 * @param col The color to convert
53 * @param withAlpha if {@code true} and alpha value < 255, return 8-digit color code, else always 6-digit
54 * @return the HTML color code (6 or 8 digit)
55 * @since 6655
56 */
57 public static String color2html(Color col, boolean withAlpha) {
58 if (col == null)
59 return null;
60 String code = "#"+int2hex(col.getRed())+int2hex(col.getGreen())+int2hex(col.getBlue());
61 if (withAlpha) {
62 int alpha = col.getAlpha();
63 if (alpha < 255) {
64 code += int2hex(alpha);
65 }
66 }
67 return code;
68 }
69}
Note: See TracBrowser for help on using the repository browser.