zoukankan      html  css  js  c++  java
  • Golang 使用FreeType-go进行字体

         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: }
  • 相关阅读:
    3139:[HNOI2013]比赛
    3143: [Hnoi2013]游走
    目前游戏行业内部主要几款游戏引擎的技术对比
    6.使用AngularJS模板来创建视图
    css选择器(E[att^=”val”]序号选择器)
    5.把作用域实现为数据模型
    4.了解AngularJS模块和依赖注入
    3.创建基本的AngularJS应用
    2.AngularJS MVC
    1.AngularJS初探
  • 原文地址:https://www.cnblogs.com/ghj1976/p/3445568.html
Copyright © 2011-2022 走看看