-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcolor.go
105 lines (100 loc) · 2.48 KB
/
color.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package xwidget
import (
"image/color"
"fyne.io/fyne/v2/theme"
)
func primaryFadedColor(fade uint8) color.Color {
r, g, b, a := ToNRGBA(theme.PrimaryColor())
faded := uint8(a) / fade
return &color.NRGBA{R: uint8(r), G: uint8(g), B: uint8(b), A: faded}
}
// ToNRGBA converts a color to RGBA values which are not premultiplied, unlike color.RGBA().
func ToNRGBA(c color.Color) (r, g, b, a int) {
// We use UnmultiplyAlpha with RGBA, RGBA64, and unrecognized implementations of Color.
// It works for all Colors whose RGBA() method is implemented according to spec, but is only necessary for those.
// Only RGBA and RGBA64 have components which are already premultiplied.
switch col := c.(type) {
// NRGBA and NRGBA64 are not premultiplied
case color.NRGBA:
r = int(col.R)
g = int(col.G)
b = int(col.B)
a = int(col.A)
case *color.NRGBA:
r = int(col.R)
g = int(col.G)
b = int(col.B)
a = int(col.A)
case color.NRGBA64:
r = int(col.R) >> 8
g = int(col.G) >> 8
b = int(col.B) >> 8
a = int(col.A) >> 8
case *color.NRGBA64:
r = int(col.R) >> 8
g = int(col.G) >> 8
b = int(col.B) >> 8
a = int(col.A) >> 8
// Gray and Gray16 have no alpha component
case *color.Gray:
r = int(col.Y)
g = int(col.Y)
b = int(col.Y)
a = 0xff
case color.Gray:
r = int(col.Y)
g = int(col.Y)
b = int(col.Y)
a = 0xff
case *color.Gray16:
r = int(col.Y) >> 8
g = int(col.Y) >> 8
b = int(col.Y) >> 8
a = 0xff
case color.Gray16:
r = int(col.Y) >> 8
g = int(col.Y) >> 8
b = int(col.Y) >> 8
a = 0xff
// Alpha and Alpha16 contain only an alpha component.
case color.Alpha:
r = 0xff
g = 0xff
b = 0xff
a = int(col.A)
case *color.Alpha:
r = 0xff
g = 0xff
b = 0xff
a = int(col.A)
case color.Alpha16:
r = 0xff
g = 0xff
b = 0xff
a = int(col.A) >> 8
case *color.Alpha16:
r = 0xff
g = 0xff
b = 0xff
a = int(col.A) >> 8
default: // RGBA, RGBA64, and unknown implementations of Color
r, g, b, a = unmultiplyAlpha(c)
}
return
}
// unmultiplyAlpha returns a color's RGBA components as 8-bit integers by calling c.RGBA() and then removing the alpha premultiplication.
// It is only used by ToRGBA.
func unmultiplyAlpha(c color.Color) (r, g, b, a int) {
red, green, blue, alpha := c.RGBA()
if alpha != 0 && alpha != 0xffff {
red = (red * 0xffff) / alpha
green = (green * 0xffff) / alpha
blue = (blue * 0xffff) / alpha
}
// 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
}