-
Notifications
You must be signed in to change notification settings - Fork 104
/
colors.go
70 lines (62 loc) · 1.18 KB
/
colors.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
package render
import (
"fmt"
"image/color"
"strings"
)
func ParseColor(scol string) (color.Color, error) {
var format string
var fourBits bool
var hasAlpha bool
scol = strings.TrimPrefix(scol, "#")
switch len(scol) {
case 3:
format = "%1x%1x%1x"
fourBits = true
hasAlpha = false
case 4:
format = "%1x%1x%1x%1x"
fourBits = true
hasAlpha = true
case 6:
format = "%02x%02x%02x"
fourBits = false
hasAlpha = false
case 8:
format = "%02x%02x%02x%02x"
fourBits = false
hasAlpha = true
default:
return color.Gray{0}, fmt.Errorf("color: %v is not a hex-color", scol)
}
var r, g, b, a uint8
if hasAlpha {
n, err := fmt.Sscanf(scol, format, &r, &g, &b, &a)
if err != nil {
return color.Gray{0}, err
}
if n != 4 {
return color.Gray{0}, fmt.Errorf("color: %v is not a hex-color", scol)
}
} else {
n, err := fmt.Sscanf(scol, format, &r, &g, &b)
if err != nil {
return color.Gray{0}, err
}
if n != 3 {
return color.Gray{0}, fmt.Errorf("color: %v is not a hex-color", scol)
}
if fourBits {
a = 15
} else {
a = 255
}
}
if fourBits {
r |= r << 4
g |= g << 4
b |= b << 4
a |= a << 4
}
return color.NRGBA{r, g, b, a}, nil
}