From 22038b61ff1784259485670e4d9d3ba4d73349c2 Mon Sep 17 00:00:00 2001 From: Nuno Cruces Date: Sun, 28 Mar 2021 00:23:28 +0000 Subject: [PATCH] Clamp colors. --- internal/zenutil/color.go | 9 ++++++++- internal/zenutil/color_test.go | 36 ++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 internal/zenutil/color_test.go diff --git a/internal/zenutil/color.go b/internal/zenutil/color.go index f2a0b2e..8388270 100644 --- a/internal/zenutil/color.go +++ b/internal/zenutil/color.go @@ -35,7 +35,14 @@ func ParseColor(s string) color.Color { var a float32 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 } } diff --git a/internal/zenutil/color_test.go b/internal/zenutil/color_test.go new file mode 100644 index 0000000..6c1210a --- /dev/null +++ b/internal/zenutil/color_test.go @@ -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) + } + } +}