From 8a67b5f840851fbe79a508eb8159b93d37e9a70e Mon Sep 17 00:00:00 2001 From: Andy Williams Date: Thu, 18 Feb 2021 17:30:46 +0000 Subject: [PATCH] Fix un-pre-mul alpha calculations Fixes #1970 --- dialog/color.go | 28 +++++++++++++++++----------- dialog/color_test.go | 18 ++++++++++++++++++ 2 files changed, 35 insertions(+), 11 deletions(-) diff --git a/dialog/color.go b/dialog/color.go index f65b241e14..0e37442e12 100644 --- a/dialog/color.go +++ b/dialog/color.go @@ -245,17 +245,7 @@ func colorToRGBA(c color.Color) (r, g, b, a int) { b = int(col.B) a = int(col.A) default: - red, green, blue, alpha := c.RGBA() - if alpha != 0 && alpha != 1 { - red /= alpha - green /= alpha - blue /= alpha - } - // Convert from range 0-65535 to range 0-255 - r = int(float64(red) / 255.0) - g = int(float64(green) / 255.0) - b = int(float64(blue) / 255.0) - a = int(float64(alpha) / 255.0) + r, g, b, a = unmultiplyAlpha(c) } return } @@ -354,3 +344,19 @@ func hueToChannel(h, v1, v2 float64) float64 { } return v2 } + +func unmultiplyAlpha(c color.Color) (r, g, b, a int) { + red, green, blue, alpha := c.RGBA() + if alpha != 0 && alpha != 0xffff { + ratio := float64(alpha) / 0xffff + red = uint32(float64(red) / ratio) + green = uint32(float64(green) / ratio) + blue = uint32(float64(blue) / ratio) + } + // Convert from range 0-65535 to range 0-255 + r = int(red >> 8) + g = int(green >> 8) + b = int(blue >> 8) + a = int(alpha >> 8) + return +} diff --git a/dialog/color_test.go b/dialog/color_test.go index 80379c98be..861cd66c70 100644 --- a/dialog/color_test.go +++ b/dialog/color_test.go @@ -380,3 +380,21 @@ func Test_hueToChannel(t *testing.T) { }) } } + +func Test_UnmultiplyAlpha(t *testing.T) { + c := color.RGBA{R: 100, G: 100, B: 100, A: 100} + r, g, b, a := unmultiplyAlpha(c) + + assert.Equal(t, 255, r) + assert.Equal(t, 255, g) + assert.Equal(t, 255, b) + assert.Equal(t, 100, a) + + c = color.RGBA{R: 100, G: 100, B: 100, A: 255} + r, g, b, a = unmultiplyAlpha(c) + + assert.Equal(t, 100, r) + assert.Equal(t, 100, g) + assert.Equal(t, 100, b) + assert.Equal(t, 255, a) +}