Created
April 3, 2025 12:14
-
-
Save zyriab/787c5d8b534506b85b9bd39a5a331a79 to your computer and use it in GitHub Desktop.
Better hex color code generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package colorizer | |
import ( | |
"fmt" | |
"math" | |
"math/rand" | |
) | |
const ( | |
ratio float64 = 1 / math.Phi | |
saturation float64 = 0.5 | |
value float64 = 0.95 | |
) | |
func RandomHex() string { | |
red, green, blue := randomRGB(rand.Float64()) | |
return "#" + getHex(red) + getHex(green) + getHex(blue) | |
} | |
func getHex(num int) string { | |
hex := fmt.Sprintf("%x", num) | |
if len(hex) == 1 { | |
hex = "0" + hex | |
} | |
return hex | |
} | |
func randomRGB(hueSeed float64) (int, int, int) { | |
hueSeed += ratio | |
hueSeed = math.Mod(hueSeed, 1) | |
return hsvToRGB(hueSeed, saturation, value) | |
} | |
func hsvToRGB(hue, saturation, value float64) (int, int, int) { | |
segmentIndex := int(hue * 6) | |
fractionalPart := hue*6 - float64(segmentIndex) | |
minComponent := value * (1 - saturation) | |
decreasingComponent := value * (1 - fractionalPart*saturation) | |
increasingComponent := value * (1 - (1-fractionalPart)*saturation) | |
var ( | |
red float64 | |
green float64 | |
blue float64 | |
) | |
switch segmentIndex { | |
case 0: | |
red, green, blue = value, increasingComponent, minComponent | |
case 1: | |
red, green, blue = decreasingComponent, value, minComponent | |
case 2: | |
red, green, blue = minComponent, value, increasingComponent | |
case 3: | |
red, green, blue = minComponent, decreasingComponent, value | |
case 4: | |
red, green, blue = increasingComponent, minComponent, value | |
case 5: | |
red, green, blue = value, minComponent, decreasingComponent | |
} | |
return int(red * 255), int(green * 255), int(blue * 255) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We're using the HSV color space, as opposed to other OSS implementations that use the darker RGB color space.
You can read more about it here.
Also thanks to AvraamMavridis/randomcolor for the
getHex
function.