Skip to content

Instantly share code, notes, and snippets.

@dadencukillia
Last active August 23, 2023 11:50
Show Gist options
  • Save dadencukillia/033dd589c910927c3e77d4af3744893d to your computer and use it in GitHub Desktop.
Save dadencukillia/033dd589c910927c3e77d4af3744893d to your computer and use it in GitHub Desktop.
add label to *Image.RGBA golang
package labeltorgba
import (
"image"
"github.com/golang/freetype"
"github.com/golang/freetype/truetype"
)
func addLabel(text string, canvas **image.RGBA, centerX int, centerY int, fontSize int, fontPath string) {
fontBytes, err := os.ReadFile(fontPath)
if err != nil {
log.Fatal(err)
}
font, err := truetype.Parse(fontBytes)
if err != nil {
log.Fatal(err)
}
ctx := freetype.NewContext()
ctx.SetDPI(72)
ctx.SetFont(font)
ctx.SetFontSize(float64(fontSize))
ctx.SetSrc(image.NewUniform(color.Transparent))
ctx.SetDst(*canvas)
ctx.SetClip((*canvas).Bounds())
bounds, _ := ctx.DrawString(text, freetype.Pt(0, 0))
ctx = freetype.NewContext()
ctx.SetDPI(72)
ctx.SetFont(font)
ctx.SetFontSize(float64(fontSize))
ctx.SetSrc(image.NewUniform(color.White))
ctx.SetDst(*canvas)
ctx.SetClip((*canvas).Bounds())
x := centerX - bounds.X.Round()/2
y := centerY - bounds.Y.Round()/2
ctx.DrawString(text, freetype.Pt(x, y))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment