fogleman / gg

Go Graphics - 2D rendering in Go with a simple API.
https://godoc.org/github.com/fogleman/gg
MIT License
4.37k stars 354 forks source link

How to draw several strings of different size and load font data only once? #141

Open lz1998 opened 3 years ago

HeCorr commented 3 years ago

You can use Scale/ScaleAbout but if you scale it too much the text might become pixelated. (Choosing a bigger font size and scaling it down as opposed to up might avoid that)

Now, if you want to load the font face once and change the font size later, I don't think that's possible.

The best you can do is read the font file once and define the font faces with the different sizes manually.

This code should work but I didn't test it:

(Edit: it seems that SetFontFace is currently broken/gives different results from LoadFontFace. see #76)

// read font file
fontBytes, err := ioutil.ReadFile(fontFilePath)
if err != nil {
    // handle error
}
// parse font
f, err := truetype.Parse(fontBytes)
if err != nil {
    // handle error
}

// define new font face and set it on the context
dc.SetFontFace(truetype.NewFace(f, &truetype.Options{Size: 60}))
dc.DrawString("big", 0, 0)

// again, but with a different size
dc.SetFontFace(truetype.NewFace(f, &truetype.Options{Size: 30}))
dc.DrawString("small", 0, 0)

(Parts of this code were taken from here)

I recommend you create separate functions for loading the font file and defining the font face so your code ends up cleaner. :)