FreeType庫(http://www.freetype.org/)是一個完全免費(開源)的、高質量的且可移植的字體引擎,它提供統一的接口來訪問多種字體格式文件,包括TrueType, OpenType, Type1, CID, CFF, Windows FON/FNT, X11 PCF等。支持單色位圖、反走樣位圖的渲染。
freetype-go就是用go語言實現了FreeType驅動。它的項目地址: https://code.google.com/p/freetype-go
下面是使用它繪制的一個字體效果圖:
相關代碼:
1: package main
2:
3: import (
4: "code.google.com/p/freetype-go/freetype"
5: "fmt"
6: "image"
7: "image/color"
8: "image/png"
9: "io/ioutil"
10: "log"
11: "os"
12: )
13:
14: const (
15: dx = 100 // 圖片的大小 寬度
16: dy = 40 // 圖片的大小 高度
17: fontFile = "RAVIE.TTF" // 需要使用的字體文件
18: fontSize = 20 // 字體尺寸
19: fontDPI = 72 // 屏幕每英寸的分辨率
20: )
21:
22: func main() {
23:
24: // 需要保存的文件
25: imgcounter := 123
26: imgfile, _ := os.Create(fmt.Sprintf("%03d.png", imgcounter))
27: defer imgfile.Close()
28:
29: // 新建一個 指定大小的 RGBA位圖
30: img := image.NewNRGBA(image.Rect(0, 0, dx, dy))
31:
32: // 畫背景
33: for y := 0; y < dy; y++ {
34: for x := 0; x < dx; x++ {
35: // 設置某個點的顏色,依次是 RGBA
36: img.Set(x, y, color.RGBA{uint8(x), uint8(y), 0, 255})
37: }
38: }
39:
40: // 讀字體數據
41: fontBytes, err := ioutil.ReadFile(fontFile)
42: if err != nil {
43: log.Println(err)
44: return
45: }
46: font, err := freetype.ParseFont(fontBytes)
47: if err != nil {
48: log.Println(err)
49: return
50: }
51:
52: c := freetype.NewContext()
53: c.SetDPI(fontDPI)
54: c.SetFont(font)
55: c.SetFontSize(fontSize)
56: c.SetClip(img.Bounds())
57: c.SetDst(img)
58: c.SetSrc(image.White)
59:
60: pt := freetype.Pt(10, 10+int(c.PointToFix32(fontSize)>>8)) // 字出現的位置
61:
62: _, err = c.DrawString("ABCDE", pt)
63: if err != nil {
64: log.Println(err)
65: return
66: }
67:
68: // 以PNG格式保存文件
69: err = png.Encode(imgfile, img)
70: if err != nil {
71: log.Fatal(err)
72: }
73:
74: }