Debian Codegraph @

src/com/bulenkov/iconloader/util/ColorUtil.java

raw symbols SCIP
1 /*
2 * Copyright 2000-2014 JetBrains s.r.o.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.bulenkov.iconloader.util;
18
19 import java.awt.*;
20
21 /**
22 * @author Konstantin Bulenkov
23 */
24 public class ColorUtil {
25 private static int shift(int colorComponent, double d) {
26 final int n = (int) (colorComponent * d);
27 return n > 255 ? 255 : n < 0 ? 0 : n;
28 }
29
30 public static Color shift(Color c, double d) {
31 return new Color(shift(c.getRed(), d), shift(c.getGreen(), d), shift(c.getBlue(), d), c.getAlpha());
32 }
33
34 public static Color toAlpha(Color color, int a) {
35 Color c = color != null ? color : Color.black;
36 return new Color(c.getRed(), c.getGreen(), c.getBlue(), a);
37 }
38
39 /**
40 * Return Color object from string. The following formats are allowed:
41 * <code>#abc123</code>,
42 * <code>ABC123</code>,
43 * <code>ab5</code>,
44 * <code>#FFF</code>.
45 *
46 * @param str hex string
47 * @return Color object
48 */
49 public static Color fromHex(String str) {
50 if (str.startsWith("#")) {
51 str = str.substring(1);
52 }
53 if (str.length() == 3) {
54 return new Color(
55 17 * Integer.valueOf(String.valueOf(str.charAt(0)), 16),
56 17 * Integer.valueOf(String.valueOf(str.charAt(1)), 16),
57 17 * Integer.valueOf(String.valueOf(str.charAt(2)), 16));
58 } else if (str.length() == 6) {
59 return Color.decode("0x" + str);
60 } else {
61 throw new IllegalArgumentException("Should be String of 3 or 6 chars length.");
62 }
63 }
64
65 public static Color fromHex(String str, Color defaultValue) {
66 try {
67 return fromHex(str);
68 } catch (Exception e) {
69 return defaultValue;
70 }
71 }
72
73 /**
74 * Checks whether color is dark or not based on perceptional luminosity
75 * http://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color
76 *
77 * @param c color to check
78 * @return dark or not
79 */
80 public static boolean isDark(final Color c) {
81 // based on perceptional luminosity, see
82 return (1 - (0.299 * c.getRed() + 0.587 * c.getGreen() + 0.114 * c.getBlue()) / 255) >= 0.5;
83 }
84 }