-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathhex.go
92 lines (71 loc) · 1.93 KB
/
hex.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 colors
import (
"fmt"
"regexp"
"strings"
)
const (
hexRegexString = "^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$"
hexFormat = "#%02x%02x%02x"
hexShortFormat = "#%1x%1x%1x"
hexToRGBFactor = 17
)
var (
hexRegex = regexp.MustCompile(hexRegexString)
)
// HEXColor represents a HEX color
type HEXColor struct {
hex string
}
// ParseHEX validates an parses the provided string into a HEXColor object
func ParseHEX(s string) (*HEXColor, error) {
s = strings.ToLower(s)
if !hexRegex.MatchString(s) {
return nil, ErrBadColor
}
return &HEXColor{hex: s}, nil
}
// String returns the string representation on the HEXColor
func (c *HEXColor) String() string {
return c.hex
}
// ToHEX converts the HEXColor to a HEXColor
// it's here to satisfy the Color interface
func (c *HEXColor) ToHEX() *HEXColor {
return c
}
// ToRGB converts the HEXColor to and RGBColor
func (c *HEXColor) ToRGB() *RGBColor {
var r, g, b uint8
if len(c.hex) == 4 {
fmt.Sscanf(c.hex, hexShortFormat, &r, &g, &b)
r *= hexToRGBFactor
g *= hexToRGBFactor
b *= hexToRGBFactor
} else {
fmt.Sscanf(c.hex, hexFormat, &r, &g, &b)
}
return &RGBColor{R: r, G: g, B: b}
}
// ToRGBA converts the HEXColor to an RGBAColor
func (c *HEXColor) ToRGBA() *RGBAColor {
rgb := c.ToRGB()
return &RGBAColor{R: rgb.R, G: rgb.G, B: rgb.B, A: 1}
}
// IsLight returns whether the color is perceived to be a light color
func (c *HEXColor) IsLight() bool {
return c.ToRGB().IsLight()
}
// IsDark returns whether the color is perceived to be a dark color
func (c *HEXColor) IsDark() bool {
return !c.IsLight()
}
// RGBA implements color.Color interface.
// It returns the red, green, blue and alpha values for the color. Each value ranges within [0, 0xffff]
func (c *HEXColor) RGBA() (r, g, b, a uint32) {
return c.ToRGBA().RGBA()
}
// Equal reports whether c is the same color as d
func (c *HEXColor) Equal(d Color) bool {
return c.ToRGBA().String() == d.ToRGBA().String()
}