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

Last change on this file since 8393 was 8345, checked in by Don-vip, 9 years ago

code style - Useless parentheses around expressions should be removed to prevent any misunderstanding

  • Property svn:eol-style set to native
File size: 2.3 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() == 3) {
24 return html2color(new String(
25 new char[]{html.charAt(0), html.charAt(0), html.charAt(1), html.charAt(1), html.charAt(2), html.charAt(2)}));
26 }
27 if (html.length() != 6 && html.length() != 8)
28 return null;
29 try {
30 return new Color(
31 Integer.parseInt(html.substring(0,2),16),
32 Integer.parseInt(html.substring(2,4),16),
33 Integer.parseInt(html.substring(4,6),16),
34 html.length() == 8 ? Integer.parseInt(html.substring(6,8),16) : 255);
35 } catch (NumberFormatException e) {
36 return null;
37 }
38 }
39
40 private static String int2hex(int i) {
41 String s = Integer.toHexString(i / 16) + Integer.toHexString(i % 16);
42 return s.toUpperCase();
43 }
44
45 /**
46 * Returns the HTML color code (6 or 8 digit).
47 * @param col The color to convert
48 * @return the HTML color code (6 or 8 digit)
49 */
50 public static String color2html(Color col) {
51 return color2html(col, true);
52 }
53
54 /**
55 * Returns the HTML color code (6 or 8 digit).
56 * @param col The color to convert
57 * @param withAlpha if {@code true} and alpha value < 255, return 8-digit color code, else always 6-digit
58 * @return the HTML color code (6 or 8 digit)
59 * @since 6655
60 */
61 public static String color2html(Color col, boolean withAlpha) {
62 if (col == null)
63 return null;
64 String code = "#"+int2hex(col.getRed())+int2hex(col.getGreen())+int2hex(col.getBlue());
65 if (withAlpha) {
66 int alpha = col.getAlpha();
67 if (alpha < 255) {
68 code += int2hex(alpha);
69 }
70 }
71 return code;
72 }
73}
Note: See TracBrowser for help on using the repository browser.