2020-01-19 06:57:05 -05:00
|
|
|
package zenutil
|
2020-01-18 23:28:06 -05:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"image/color"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"golang.org/x/image/colornames"
|
|
|
|
)
|
|
|
|
|
2020-01-29 11:45:40 -05:00
|
|
|
// ParseColor is internal.
|
2020-01-18 23:28:06 -05:00
|
|
|
func ParseColor(s string) color.Color {
|
|
|
|
if len(s) == 4 || len(s) == 5 {
|
|
|
|
c := color.NRGBA{A: 0xf}
|
|
|
|
n, _ := fmt.Sscanf(s, "#%1x%1x%1x%1x", &c.R, &c.G, &c.B, &c.A)
|
|
|
|
c.R, c.G, c.B, c.A = c.R*0x11, c.G*0x11, c.B*0x11, c.A*0x11
|
|
|
|
if n >= 3 {
|
|
|
|
return c
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(s) == 7 || len(s) == 9 {
|
|
|
|
c := color.NRGBA{A: 0xff}
|
|
|
|
n, _ := fmt.Sscanf(s, "#%02x%02x%02x%02x", &c.R, &c.G, &c.B, &c.A)
|
|
|
|
if n >= 3 {
|
|
|
|
return c
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-26 11:36:53 -04:00
|
|
|
if len(s) >= 10 && "rgb" == s[:3] {
|
2020-01-18 23:28:06 -05:00
|
|
|
c := color.NRGBA{A: 0xff}
|
2021-03-05 21:29:00 -05:00
|
|
|
if _, err := fmt.Sscanf(s, "rgb(%d,%d,%d)", &c.R, &c.G, &c.B); err == nil {
|
2020-01-18 23:28:06 -05:00
|
|
|
return c
|
|
|
|
}
|
|
|
|
|
|
|
|
var a float32
|
2021-03-05 21:29:00 -05:00
|
|
|
if _, err := fmt.Sscanf(s, "rgba(%d,%d,%d,%f)", &c.R, &c.G, &c.B, &a); err == nil {
|
2021-03-27 20:23:28 -04:00
|
|
|
switch {
|
|
|
|
case a <= 0:
|
|
|
|
c.A = 0
|
|
|
|
case a >= 1:
|
|
|
|
c.A = 255
|
|
|
|
default:
|
|
|
|
c.A = uint8(255*a + 0.5)
|
|
|
|
}
|
2020-01-18 23:28:06 -05:00
|
|
|
return c
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-06-18 11:16:04 -04:00
|
|
|
c, ok := colornames.Map[strings.ToLower(s)]
|
|
|
|
if ok {
|
|
|
|
return c
|
|
|
|
}
|
|
|
|
return nil
|
2020-01-21 11:13:45 -05:00
|
|
|
}
|
|
|
|
|
2020-01-29 11:45:40 -05:00
|
|
|
// UnparseColor is internal.
|
2020-01-21 11:13:45 -05:00
|
|
|
func UnparseColor(c color.Color) string {
|
|
|
|
n := color.NRGBAModel.Convert(c).(color.NRGBA)
|
|
|
|
if n.A == 255 {
|
|
|
|
return fmt.Sprintf("rgb(%d,%d,%d)", n.R, n.G, n.B)
|
|
|
|
} else {
|
|
|
|
return fmt.Sprintf("rgba(%d,%d,%d,%f)", n.R, n.G, n.B, float32(n.A)/255)
|
|
|
|
}
|
2020-01-18 23:28:06 -05:00
|
|
|
}
|
2021-07-07 08:24:46 -04:00
|
|
|
|
|
|
|
// ColorEquals is internal.
|
|
|
|
func ColorEquals(c1, c2 color.Color) bool {
|
|
|
|
if c1 == nil || c2 == nil {
|
|
|
|
return c1 == c2
|
|
|
|
}
|
|
|
|
r1, g1, b1, a1 := c1.RGBA()
|
|
|
|
r2, g2, b2, a2 := c2.RGBA()
|
|
|
|
return r1 == r2 && g1 == g2 && b1 == b2 && a1 == a2
|
|
|
|
}
|