-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcolors.go
92 lines (79 loc) · 1.8 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package goannular
import (
"errors"
"fmt"
"image/color"
"math/rand"
)
type Colors struct {
palette []string
numColorsInPalette int
palettes [][]string
numPalettes int
}
func (c *Colors) SetRandomPalette() {
c.palette = c.palettes[rand.Intn(c.numPalettes)]
c.numColorsInPalette = len(c.palette)
}
func (c *Colors) RandomColorHex() string {
if c.palette == nil {
c.SetRandomPalette()
}
return c.palette[rand.Intn(c.numColorsInPalette)]
}
func (c *Colors) RandomColorRGBA() color.RGBA {
h := c.RandomColorHex()
rgba, err := parseHexColorFast(h)
if err != nil {
fmt.Println(err.Error())
}
return rgba
}
func (c *Colors) RandomColorOrBlackHex() string {
if c.palette == nil {
c.SetRandomPalette()
}
palette := append(c.palette, "#000000")
return palette[rand.Intn(c.numColorsInPalette+1)]
}
func (c *Colors) RandomColorOrBlackRGBA() color.RGBA {
h := c.RandomColorOrBlackHex()
rgba, err := parseHexColorFast(h)
if err != nil {
fmt.Println(err.Error())
}
return rgba
}
// https://stackoverflow.com/questions/54197913/parse-hex-string-to-image-color
func parseHexColorFast(s string) (c color.RGBA, err error) {
var errInvalidFormat = errors.New("invalid format")
c.A = 0xff
if s[0] != '#' {
return c, errInvalidFormat
}
hexToByte := func(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
}
err = errInvalidFormat
return 0
}
switch len(s) {
case 7:
c.R = hexToByte(s[1])<<4 + hexToByte(s[2])
c.G = hexToByte(s[3])<<4 + hexToByte(s[4])
c.B = hexToByte(s[5])<<4 + hexToByte(s[6])
case 4:
c.R = hexToByte(s[1]) * 17
c.G = hexToByte(s[2]) * 17
c.B = hexToByte(s[3]) * 17
default:
err = errInvalidFormat
}
return
}