1 // Copyright (c) 2012 Rodrigo Moraes. All rights reserved.
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are
7 // * Redistributions of source code must retain the above copyright
8 // notice, this list of conditions and the following disclaimer.
9 // * Redistributions in binary form must reproduce the above
10 // copyright notice, this list of conditions and the following disclaimer
11 // in the documentation and/or other materials provided with the
13 // * Neither the name of Google Inc. nor the names of its
14 // contributors may be used to endorse or promote products derived from
15 // this software without specific prior written permission.
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 // HSLModel converts any color.Color to a HSL color.
37 var HSLModel = color.ModelFunc(hslModel)
39 // HSL represents a cylindrical coordinate of points in an RGB color model.
41 // Values are in the range 0 to 1.
46 // RGBA returns the alpha-premultiplied red, green, blue and alpha values
48 func (c HSL) RGBA() (uint32, uint32, uint32, uint32) {
49 r, g, b := HSLToRGB(c.H, c.S, c.L)
50 return uint32(r) * 0x101, uint32(g) * 0x101, uint32(b) * 0x101, 0xffff
53 // hslModel converts a color.Color to HSL.
54 func hslModel(c color.Color) color.Color {
55 if _, ok := c.(HSL); ok {
58 r, g, b, _ := c.RGBA()
59 h, s, l := RGBToHSL(uint8(r>>8), uint8(g>>8), uint8(b>>8))
63 // RGBToHSL converts an RGB triple to a HSL triple.
64 func RGBToHSL(r, g, b uint8) (h, s, l float64) {
65 fR := float64(r) / 255
66 fG := float64(g) / 255
67 fB := float64(b) / 255
68 max := math.Max(math.Max(fR, fG), fB)
69 min := math.Min(math.Min(fR, fG), fB)
78 s = d / (2.0 - max - min)
98 // HSLToRGB converts an HSL triple to a RGB triple.
99 func HSLToRGB(h, s, l float64) (r, g, b uint8) {
100 var fR, fG, fB float64
111 fR = hueToRGB(p, q, h+1.0/3)
112 fG = hueToRGB(p, q, h)
113 fB = hueToRGB(p, q, h-1.0/3)
115 r = uint8((fR * 255) + 0.5)
116 g = uint8((fG * 255) + 0.5)
117 b = uint8((fB * 255) + 0.5)
121 // hueToRGB is a helper function for HSLToRGB.
122 func hueToRGB(p, q, t float64) float64 {
136 return p + (q-p)*(2.0/3-t)*6