-
Notifications
You must be signed in to change notification settings - Fork 1
/
hexcolor.go
80 lines (69 loc) · 1.49 KB
/
hexcolor.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
// Copyright 2020 6543. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package hexcolor
import (
"fmt"
"image/color"
"strconv"
"strings"
)
// HexColor represents a single hex color
type HexColor struct {
original string
hex string
}
// NewHexColor convert string into a HexColor
func NewHexColor(hc string) (*HexColor, error) {
c := &HexColor{original: hc}
hc = strings.TrimLeft(strings.ToLower(hc), "#")
if _, err := strconv.ParseUint(hc, 16, 24); err == nil {
if len(hc) == 6 {
c.hex = hc
return c, nil
}
if len(hc) == 3 {
c.hex = string([]byte{hc[0], hc[0], hc[1], hc[1], hc[2], hc[2]})
return c, nil
}
}
// handle named colors
return nil, fmt.Errorf("Malformed color: %s", hc)
}
// ToString return normalized hex code of color
func (c *HexColor) ToString() string {
if c == nil {
return ""
}
return c.hex
}
// ToRGBA return RGBA color
func (c *HexColor) ToRGBA() (*color.RGBA, error) {
if c == nil {
return nil, nil
}
var r, g, b uint8
if _, err := fmt.Sscanf(c.hex, "%2x%2x%2x", &r, &g, &b); err != nil {
return nil, err
}
return &color.RGBA{
R: r,
G: g,
B: b,
A: 0xff,
}, nil
}
// ToHexColor convert RGBA to HexColor
func ToHexColor(c *color.RGBA) *HexColor {
toS := func(i uint8) string {
h := fmt.Sprintf("%x", i)
if len(h) == 1 {
h = "0" + h
}
return h
}
return &HexColor{
original: fmt.Sprintf("%v", c),
hex: toS(c.R) + toS(c.G) + toS(c.B),
}
}