golang.org/x/image/font
包只是爲圖像上的字體面和繪圖文本定義接口。
您可以使用Freetype字體光柵化器的執行:github.com/golang/freetype
。
關鍵類型是freetype.Context
,它有你需要的所有方法。
有關完整的示例,請查看此文件:example/freetype/main.go
。此示例加載字體文件,創建並配置freetype.Context
,在圖像上繪製文本並將結果圖像保存到文件。
讓我們假設你已經加載了字體文件,並配置了一個c
上下文(請參閱示例如何做)。然後你addLabel()
功能看起來是這樣的:
func addLabel(img *image.RGBA, x, y int, label string) {
c.SetDst(img)
size := 12.0 // font size in pixels
pt := freetype.Pt(x, y+int(c.PointToFixed(size)>>6))
if _, err := c.DrawString(label, pt); err != nil {
// handle error
}
}
如果你不想與freetype
包和外部的字體文件麻煩,在font/basicfont
包包含一個名爲Face7x13
其圖形數據的基本字體是完全獨立的。這是你如何可以使用:
import (
"golang.org/x/image/font"
"golang.org/x/image/font/basicfont"
"golang.org/x/image/math/fixed"
"image"
"image/color"
)
func addLabel(img *image.RGBA, x, y int, label string) {
col := color.RGBA{200, 100, 0, 255}
point := fixed.Point26_6{fixed.Int26_6(x * 64), fixed.Int26_6(y * 64)}
d := &font.Drawer{
Dst: img,
Src: image.NewUniform(col),
Face: basicfont.Face7x13,
Dot: point,
}
d.DrawString(label)
}
這是本addLabel()
功能如何使用:下面的代碼創建一個新的形象,借鑑了它的"Hello Go"
文本和一個名爲hello-go.png
文件並將其保存:
func main() {
img := image.NewRGBA(image.Rect(0, 0, 300, 100))
addLabel(img, 20, 30, "Hello Go")
f, err := os.Create("hello-go.png")
if err != nil {
panic(err)
}
defer f.Close()
if err := png.Encode(f, img); err != nil {
panic(err)
}
}
注意上面的代碼也需要導入"image/png"
包。請注意0座標是文字的底線。所以如果你想畫一條線到左上角,你必須使用x = 0
和y = 13
(13是這個Face7x13
字體的高度)。如果您願意,您可以通過從y
座標中減去13
來將其構建到addLabel()
函數中,以便傳遞的y
座標將成爲繪製文本的頂部座標。
還有在golang.org/x/image/font/inconsolata
包定期和大膽的風格額外的自包含的字體,使用它們,您只需要指定不同的Face
在addLabel()
:
import "golang.org/x/image/font/inconsolata"
// To use regular Inconsolata font family:
Face: inconsolata.Regular8x16,
// To use bold Inconsolata font family:
Face: inconsolata.Bold8x16,
該軟件包明確指出,它只提供字體表面的接口。 ''''其他包提供了字體實現,例如,一個truetype包將提供一個基於.ttf字體文件的文件。「' –