Debian Codegraph @

vendor/github.com/xyproto/gfx/palette.go

raw
1 package gfx
2
3 import (
4 "image"
5 "image/color"
6 "image/draw"
7 "math"
8 "math/rand"
9 "sort"
10 )
11
12 // Palette is a slice of colors.
13 type Palette []color.NRGBA
14
15 // Color returns the color at index n.
16 func (p Palette) Color(n int) color.NRGBA {
17 if n >= 0 && n < p.Len() {
18 return p[n]
19 }
20
21 return color.NRGBA{}
22 }
23
24 // Len returns the number of colors in the palette.
25 func (p Palette) Len() int {
26 return len(p)
27 }
28
29 // Sort palette.
30 func (p Palette) Sort(less func(i, j int) bool) {
31 sort.Slice(p, less)
32 }
33
34 // Random color from the palette.
35 func (p Palette) Random() color.NRGBA {
36 return p[rand.Intn(p.Len())]
37 }
38
39 // Tile returns a new image based on the input image, but with colors from the palette.
40 func (p Palette) Tile(src image.Image) *Paletted {
41 dst := NewPalettedImage(src.Bounds(), p)
42
43 draw.Draw(dst, dst.Bounds(), src, image.Point{}, draw.Src)
44
45 return dst
46 }
47
48 // Convert returns the palette color closest to c in Euclidean R,G,B space.
49 func (p Palette) Convert(c color.Color) color.Color {
50 if len(p) == 0 {
51 return color.RGBA{}
52 }
53
54 return p[p.Index(c)]
55 }
56
57 // Index returns the index of the palette color closest to c in Euclidean
58 // R,G,B,A space.
59 func (p Palette) Index(c color.Color) int {
60 cr, cg, cb, ca := c.RGBA()
61 ret, bestSum := 0, uint32(1<<32-1)
62
63 for i, v := range p {
64 vr, vg, vb, va := v.RGBA()
65 sum := sqDiff(cr, vr) + sqDiff(cg, vg) + sqDiff(cb, vb) + sqDiff(ca, va)
66
67 if sum < bestSum {
68 if sum == 0 {
69 return i
70 }
71
72 ret, bestSum = i, sum
73 }
74 }
75
76 return ret
77 }
78
79 // AsColorPalette converts the Palette to a color.Palette.
80 func (p Palette) AsColorPalette() color.Palette {
81 var cp = make(color.Palette, len(p))
82
83 for i, c := range p {
84 cp[i] = c
85 }
86
87 return cp
88 }
89
90 // At returns the color at the given float64 value (range 0-1)
91 func (p Palette) At(t float64) color.Color {
92 n := len(p)
93 if t <= 0 || math.IsNaN(t) {
94 return p[0]
95 }
96 if t >= 1 {
97 return p[n-1]
98 }
99
100 i := int(math.Floor(t * float64(n-1)))
101 s := 1 / float64(n-1)
102
103 return LerpColors(p[i], p[i+1], (t-float64(i)*s)/s)
104 }
105
106 // sqDiff returns the squared-difference of x and y, shifted by 2 so that
107 // adding four of those won't overflow a uint32.
108 //
109 // x and y are both assumed to be in the range [0, 0xffff].
110 func sqDiff(x, y uint32) uint32 {
111 d := x - y
112
113 return (d * d) >> 2
114 }