Debian Codegraph @

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

raw
1 //go:build !tinygo
2 // +build !tinygo
3
4 package gfx
5
6 import (
7 "image/color"
8 "math"
9 )
10
11 // SortByHue sorts based on (HSV) Hue.
12 func (p Palette) SortByHue() {
13 p.Sort(func(i, j int) bool {
14 return ColorToHSV(p[i]).Hue > ColorToHSV(p[i]).Hue
15 })
16 }
17
18 // ColorToHSV converts a color into HSV.
19 func ColorToHSV(c color.Color) HSV {
20 var (
21 r, g, b = floatRGB(c)
22 min, max = minRGB(r, g, b), maxRGB(r, g, b)
23 h, s, v, d = max, max, max, max - min
24 )
25
26 if max == 0 {
27 s = 0
28 } else {
29 s = d / max
30 }
31
32 if max == min {
33 h = 0 // achromatic
34 } else {
35 switch max {
36 case r:
37 if g < b {
38 h = (g-b)/d + 6.0
39 } else {
40 h = (g - b) / d
41 }
42 case g:
43 h = (b-r)/d + 2.0
44 case b:
45 h = (r-g)/d + 4.0
46 }
47 }
48
49 return HSV{h, s * 100.0, v * 100.0}
50 }
51
52 // HSV is the hue, saturation and value color representation.
53 // - Hue [0,360]
54 // - Saturation [0,1]
55 // - Value [0,1]
56 type HSV struct {
57 Hue float64
58 Saturation float64
59 Value float64
60 }
61
62 // Components in HSV.
63 func (hsv HSV) Components() (h, s, v float64) {
64 return hsv.Hue, hsv.Saturation, hsv.Value
65 }
66
67 // RGBA converts a HSV color value to color.RGBA.
68 func (hsv HSV) RGBA() color.RGBA {
69 h, s, v := hsv.Components()
70
71 hprime := h / 60.0
72
73 var r, g, b float64
74
75 c := v * s
76 x := c * math.Abs(math.Remainder(hprime, 2))
77 m := v - c
78
79 switch {
80 case hprime >= 0 && hprime < 1:
81 r = c
82 g = x
83 b = 0
84 case hprime >= 1 && hprime < 2:
85 r = x
86 g = c
87 b = 0
88 case hprime >= 2 && hprime < 3:
89 r = 0
90 g = c
91 b = x
92 case hprime >= 3 && hprime < 4:
93 r = 0
94 g = x
95 b = c
96 case hprime >= 4 && hprime < 5:
97 r = x
98 g = 0
99 b = c
100 case hprime >= 5 && hprime < 6:
101 r = c
102 g = 0
103 b = x
104 }
105
106 return ColorRGBA(
107 uint8(math.Round((r+m)*255)),
108 uint8(math.Round((g+m)*255)),
109 uint8(math.Round((b+m)*255)),
110 255,
111 )
112 }