-
Notifications
You must be signed in to change notification settings - Fork 1
/
color.go
123 lines (105 loc) · 2.18 KB
/
color.go
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
115
116
117
118
119
120
121
122
123
package colorize
import (
"fmt"
baseColor "image/color"
)
type (
colorMode byte
// Color representation interface.
Color interface {
Comparable
Formatter
fmt.Stringer
Red() byte
Green() byte
Blue() byte
Alpha() byte
Hex() string
RGB() string
}
// Comparable representation interface.
Comparable interface {
Equals(Color) bool
}
// Formatter representation interface.
Formatter interface {
generate(colorMode) string
}
// color for RGB.
color struct {
Color
fmt.GoStringer
rgba baseColor.RGBA
}
)
const (
colorModeFormat = "%d;2;%#v"
colorDigitsFormat = "%d;%d;%d"
colorStringFormat = "%d.%d.%d.%d"
colorRGBFormat = "%d, %d, %d"
hexadecimalFormat = "#%02x%02x%02x"
hexadecimalShortFormat = "#%1x%1x%1x"
hexadecimalShortFormatLength = 4
)
func (clr color) Red() byte {
return clr.rgba.R
}
func (clr color) Green() byte {
return clr.rgba.G
}
func (clr color) Blue() byte {
return clr.rgba.B
}
func (clr color) Alpha() byte {
return clr.rgba.A
}
func (clr color) GoString() string {
return clr.format(
colorDigitsFormat,
clr.Red(),
clr.Green(),
clr.Blue(),
)
}
func (clr color) String() string {
return clr.format(
colorStringFormat,
clr.Red(),
clr.Green(),
clr.Blue(),
clr.Alpha(),
)
}
// Hex returns the hexadecimal representation of the color, as in #abcdef.
func (clr color) Hex() string {
return clr.format(
hexadecimalFormat,
clr.Red(),
clr.Green(),
clr.Blue(),
)
}
// RGB returns the rgb representation of the color, as in 255, 255, 255.
func (clr color) RGB() string {
return clr.format(
colorRGBFormat,
clr.Red(),
clr.Green(),
clr.Blue(),
)
}
func (clr color) Equals(color Color) bool {
return color != nil &&
clr.Red() == color.Red() &&
clr.Green() == color.Green() &&
clr.Blue() == color.Blue() &&
clr.Alpha() == color.Alpha()
}
func (clr color) format(format string, args ...interface{}) string {
return fmt.Sprintf(format, args...)
}
// generate returns a string color representation based on
// given mode (foreground or background).
func (clr color) generate(mode colorMode) string {
return clr.format(colorModeFormat, mode, clr)
}