Skip to content

Instantly share code, notes, and snippets.

@Kangaroux
Last active April 19, 2022 18:22
Show Gist options
  • Save Kangaroux/c4ffe4a677845561eedc75515b26393c to your computer and use it in GitHub Desktop.
Save Kangaroux/c4ffe4a677845561eedc75515b26393c to your computer and use it in GitHub Desktop.
Golang: Hex to RGB/RGBA
// HexToRGB converts a 24 bit hex number into its corresponding RGB color
// with 100% alpha
//
// clr := HexToRGB(0xFFAA00)
// fmt.Printf("%+v\n", clr) // {R:255 G:170 B:0 A:255}
func HexToRGB(hex uint32) color.RGBA {
r := uint8((hex & 0xFF0000) >> 16)
g := uint8((hex & 0xFF00) >> 8)
b := uint8(hex & 0xFF)
return color.RGBA{r, g, b, 255}
}
// HexToRGB converts a 32 bit hex number into its corresponding RGBA color
//
// clr := HexToRGBA(0xFFAA00BB)
// fmt.Printf("%+v\n", clr) // {R:255 G:170 B:0 A:187}
func HexToRGBA(hex uint32) color.RGBA {
r := uint8((hex & 0xFF000000) >> 24)
g := uint8((hex & 0xFF0000) >> 16)
b := uint8((hex & 0xFF00) >> 8)
a := uint8(hex & 0xFF)
return color.RGBA{r, g, b, a}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment