Clamp colors.

This commit is contained in:
Nuno Cruces 2021-03-28 00:23:28 +00:00
parent bde480b495
commit 22038b61ff
2 changed files with 44 additions and 1 deletions

View File

@ -35,7 +35,14 @@ func ParseColor(s string) color.Color {
var a float32 var a float32
if _, err := fmt.Sscanf(s, "rgba(%d,%d,%d,%f)", &c.R, &c.G, &c.B, &a); err == nil { if _, err := fmt.Sscanf(s, "rgba(%d,%d,%d,%f)", &c.R, &c.G, &c.B, &a); err == nil {
c.A = uint8(255*a + 0.5) switch {
case a <= 0:
c.A = 0
case a >= 1:
c.A = 255
default:
c.A = uint8(255*a + 0.5)
}
return c return c
} }
} }

View File

@ -0,0 +1,36 @@
package zenutil
import (
"image/color"
"testing"
"golang.org/x/image/colornames"
)
func TestColor(t *testing.T) {
tests := []string{
"chocolate",
"lime",
"olive",
"orange",
"plum",
"salmon",
"tomato",
}
eq := func(c1, c2 color.Color) bool {
r1, g1, b1, a1 := c1.RGBA()
r2, g2, b2, a2 := c2.RGBA()
return r1 == r2 && g1 == g2 && b1 == b2 && a1 == a2
}
for _, test := range tests {
c1 := colornames.Map[test]
c2 := ParseColor(test)
c3 := ParseColor(UnparseColor(c2))
if !eq(c1, c2) {
t.Errorf("ParseColor(%s) = %v, want %v", test, c2, c1)
}
if !eq(c1, c3) {
t.Errorf("ParseColor(UnparseColor(%s)) = %v, want %v", test, c3, c1)
}
}
}