Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix un-pre-mul alpha calculations #1974

Merged
merged 1 commit into from Feb 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 17 additions & 11 deletions dialog/color.go
Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}
18 changes: 18 additions & 0 deletions dialog/color_test.go
Expand Up @@ -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)
}