-
Notifications
You must be signed in to change notification settings - Fork 21
/
util.go
61 lines (53 loc) · 1.13 KB
/
util.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
package germanium
import (
"fmt"
"image/color"
)
func HexToByte(b byte) byte {
switch {
case b >= '0' && b <= '9':
return b - '0'
case b >= 'a' && b <= 'f':
return b - 'a' + 10
case b >= 'A' && b <= 'F':
return b - 'A' + 10
}
return 0
}
// ParseHexColor parses string into RGBA
func ParseHexColor(s string) (color.RGBA, error) {
c := color.RGBA{A: 255}
var err error
// Remove hash if present
if s[0] == '#' {
s = s[1:]
}
// Parse color code
switch len(s) {
case 8:
// RRGGBBAA
c.R = HexToByte(s[0])<<4 + HexToByte(s[1])
c.G = HexToByte(s[2])<<4 + HexToByte(s[3])
c.B = HexToByte(s[4])<<4 + HexToByte(s[5])
c.A = HexToByte(s[6])<<4 + HexToByte(s[7])
case 6:
// RRGGBB
c.R = HexToByte(s[0])<<4 + HexToByte(s[1])
c.G = HexToByte(s[2])<<4 + HexToByte(s[3])
c.B = HexToByte(s[4])<<4 + HexToByte(s[5])
case 4:
// RGBA
c.R = HexToByte(s[0]) * 17
c.G = HexToByte(s[1]) * 17
c.B = HexToByte(s[2]) * 17
c.A = HexToByte(s[3]) * 17
case 3:
// RGB
c.R = HexToByte(s[0]) * 17
c.G = HexToByte(s[1]) * 17
c.B = HexToByte(s[2]) * 17
default:
err = fmt.Errorf("invalid color length")
}
return c, err
}