该
golang.org/x/image/font包只定义了字体面和在图像上绘制文本接口。
您可以使用Go执行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.Enpre(f, img); err != nil { panic(err) }}注意上面的代码也需要
"image/png"导入包。
还要注意,
y给定的坐标将是文本的底行。因此,如果要在左上角画一条线,则必须使用
x = 0和
y =13(13是此
Face7x13字体的高度)。如果愿意,可以
addLabel()通过
13从
y坐标中减去来将其构建到函数中,以便传递的
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,



