gopkg.in/essentialkaos/ek.v3@v3.5.1/color/color.go (about) 1 // Package color provides methods for working with colors 2 package color 3 4 // ////////////////////////////////////////////////////////////////////////////////// // 5 // // 6 // Copyright (c) 2009-2016 Essential Kaos // 7 // Essential Kaos Open Source License <http://essentialkaos.com/ekol?en> // 8 // // 9 // ////////////////////////////////////////////////////////////////////////////////// // 10 11 import ( 12 "math" 13 14 "pkg.re/essentialkaos/ek.v3/mathutil" 15 ) 16 17 // RGB2Hex convert RGB color to Hex 18 func RGB2Hex(r, g, b int) int { 19 return r<<16 | g<<8 | b 20 } 21 22 // Hex2RGB convert Hex color to RGB 23 func Hex2RGB(h int) (int, int, int) { 24 if IsRGBA(h) { 25 return 0xFF, 0xFF, 0xFF 26 } 27 28 return h >> 16 & 0xFF, h >> 8 & 0xFF, h & 0xFF 29 } 30 31 // RGBA2Hex convert RGBA color to Hex 32 func RGBA2Hex(r, g, b, a int) int { 33 return r<<24 | g<<16 | b<<8 | a 34 } 35 36 // Hex2RGBA convert Hex color to RGBA 37 func Hex2RGBA(h int) (int, int, int, int) { 38 if h >= 0xFFFFFF { 39 return h >> 24 & 0xFF, h >> 16 & 0xFF, h >> 8 & 0xFF, h & 0xFF 40 } 41 42 return h >> 16 & 0xFF, h >> 8 & 0xFF, h & 0xFF, 0 43 } 44 45 // RGB2HSB convert RGB color to HSB (HSV) 46 func RGB2HSB(r, g, b int) (int, int, int) { 47 if r+g+b == 0 { 48 return 0, 0, 0 49 } 50 51 max := mathutil.Max(mathutil.Max(r, g), b) 52 min := mathutil.Min(mathutil.Min(r, g), b) 53 54 var ( 55 h int 56 s, bb float64 57 ) 58 59 switch max { 60 case min: 61 h = 0 62 case r: 63 h = (60*(g-b)/(max-min) + 360) % 360 64 case g: 65 h = (60*(b-r)/(max-min) + 120) 66 case b: 67 h = (60*(r-g)/(max-min) + 240) 68 } 69 70 bb = math.Ceil((float64(max) / 255.0) * 100.0) 71 72 if max != 0 { 73 fmax, fmin := float64(max), float64(min) 74 s = math.Ceil(((fmax - fmin) / fmax) * 100.0) 75 } 76 77 return h, int(s), int(bb) 78 } 79 80 // HSB2RGB convert HSB (HSV) color to RGB 81 func HSB2RGB(h, s, b int) (int, int, int) { 82 var r, g, bb float64 83 84 if h+s+b == 0 { 85 return 0, 0, 0 86 } 87 88 ts := float64(s) / 100.0 89 tb := float64(b) / 100.0 90 91 f := float64(h)/60.0 - math.Floor(float64(h)/60.0) 92 p := (tb * (1 - ts)) 93 q := (tb * (1 - f*ts)) 94 t := (tb * (1 - (1-f)*ts)) 95 96 switch (h / 60) % 6 { 97 case 0: 98 r, g, bb = tb, t, p 99 case 1: 100 r, g, bb = q, tb, p 101 case 2: 102 r, g, bb = p, tb, t 103 case 3: 104 r, g, bb = p, q, tb 105 case 4: 106 r, g, bb = t, p, tb 107 case 5: 108 r, g, bb = tb, p, q 109 } 110 111 return int(mathutil.Round(r*0xFF, 0)), 112 int(mathutil.Round(g*0xFF, 0)), 113 int(mathutil.Round(bb*0xFF, 0)) 114 } 115 116 // IsRGBA if Hex coded color has alpha channel info 117 func IsRGBA(h int) bool { 118 return h > 0xFFFFFF 119 }