导航

Golang 使用FreeType-go进行字体

Posted on 2013-11-27 14:12  蝈蝈俊  阅读(8277)  评论(1编辑  收藏  举报

     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

下面是使用它绘制的一个字体效果图:

123

相关代码:

   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: }