zenity/internal/zenutil/color.go

66 lines
1.3 KiB
Go
Raw Normal View History

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
}
}
if len(s) >= 10 {
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
}
}
2020-01-21 11:13:45 -05:00
c, ok := colornames.Map[strings.ToLower(s)]
if ok {
return c
}
return nil
}
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
}