Skip to content

Instantly share code, notes, and snippets.

@zyriab
Created April 3, 2025 12:14
Show Gist options
  • Save zyriab/787c5d8b534506b85b9bd39a5a331a79 to your computer and use it in GitHub Desktop.
Save zyriab/787c5d8b534506b85b9bd39a5a331a79 to your computer and use it in GitHub Desktop.
Better hex color code generator
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)
}
@zyriab
Copy link
Author

zyriab commented Apr 3, 2025

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment