/
RGB.java
114 lines (108 loc) · 2.72 KB
/
RGB.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/*******************************************************************************
* Copyright (c) 2014 IBM Corporation, BestSolution.at and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v.2.0 which is available at
* https://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API
* Tom Schindl<tom.schindl@bestsolution.at> - initial API and implementation
*******************************************************************************/
package org.eclipse.swt.graphics;
public class RGB {
public int red;
public int green;
public int blue;
public RGB(int red, int green, int blue) {
this.red = red;
this.green = green;
this.blue = blue;
}
public RGB(float hue, float saturation, float brightness) {
if (hue < 0 || hue > 360 || saturation < 0 || saturation > 1 ||
brightness < 0 || brightness > 1) {
throw new IllegalArgumentException();
// SWT.error(SWT.ERROR_INVALID_ARGUMENT);
}
float r, g, b;
if (saturation == 0) {
r = g = b = brightness;
} else {
if (hue == 360) hue = 0;
hue /= 60;
int i = (int)hue;
float f = hue - i;
float p = brightness * (1 - saturation);
float q = brightness * (1 - saturation * f);
float t = brightness * (1 - saturation * (1 - f));
switch(i) {
case 0:
r = brightness;
g = t;
b = p;
break;
case 1:
r = q;
g = brightness;
b = p;
break;
case 2:
r = p;
g = brightness;
b = t;
break;
case 3:
r = p;
g = q;
b = brightness;
break;
case 4:
r = t;
g = p;
b = brightness;
break;
case 5:
default:
r = brightness;
g = p;
b = q;
break;
}
}
red = (int)(r * 255 + 0.5);
green = (int)(g * 255 + 0.5);
blue = (int)(b * 255 + 0.5);
}
public float[] getHSB() {
float r = red / 255f;
float g = green / 255f;
float b = blue / 255f;
float max = Math.max(Math.max(r, g), b);
float min = Math.min(Math.min(r, g), b);
float delta = max - min;
float hue = 0;
float brightness = max;
float saturation = max == 0 ? 0 : (max - min) / max;
if (delta != 0) {
if (r == max) {
hue = (g - b) / delta;
} else {
if (g == max) {
hue = 2 + (b - r) / delta;
} else {
hue = 4 + (r - g) / delta;
}
}
hue *= 60;
if (hue < 0) hue += 360;
}
return new float[] {hue, saturation, brightness};
}
@Override
public String toString() {
return "RGB("+red+","+green+","+blue+")";
}
}