Skip to content

Instantly share code, notes, and snippets.

@AndreKR
Created Mar 14, 2017
Embed
What would you like to do?
Three ways of drawing text in go
// Initialize an empty image
dest := image.NewRGBA(image.Rect(0, 0, 800, 300))
// Draw a white background
draw.Draw(dest, dest.Bounds(), &image.Uniform{color.White}, image.ZP, draw.Src)
// Read the font
fontBytes, err := ioutil.ReadFile(exeDir + "/DejaVuSans.ttf")
if err != nil {
log.Fatal(err)
}
f, err := freetype.ParseFont(fontBytes)
if err != nil {
log.Fatal(err)
}
// Variant 1 (Freetype "high-level API")
ft := freetype.NewContext()
ft.SetDst(dest)
ft.SetFont(f)
ft.SetFontSize(8)
ft.SetDPI(96)
ft.SetClip(dest.Bounds())
ft.SetSrc(image.Black)
ft.SetHinting(font.HintingNone)
ft.DrawString("some text", freetype.Pt(100, 100))
// Variant 2 (Freetype/Go font API)
opts := &truetype.Options{}
opts.DPI = 96
opts.Size = 8
opts.Hinting = font.HintingNone
d := font.Drawer{}
d.Dst = dest
d.Src = image.Black
d.Face = truetype.NewFace(f, opts)
d.Dot = freetype.Pt(100, 120)
d.DrawString("some text")
// Variant 3 (draw2d)
gc := draw2dimg.NewGraphicContext(dest)
draw2d.RegisterFont(draw2dbase.DefaultFontData, f)
gc.SetFillColor(color.Black)
gc.SetFontSize(8)
gc.SetDPI(96)
gc.FillStringAt("some text", 100, 140)
// Write PNG
fd, err := os.Create(exeDir + "/image.png")
if err != nil {
log.Fatal(err)
}
defer fd.Close()
encoder := png.Encoder{}
encoder.CompressionLevel = png.DefaultCompression
encoder.Encode(fd, dest)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment