• freetypego学习


    freetype-go学习

    freetype-go的源码在这里https://code.google.com/p/freetype-go/

    它的作用是生成带文字的png图片

    首先解决的几个概念:

    什么是FreeType?

    FreeType是一个可移植的,高效的字体引擎。

    字体在电脑上的显示有两种方式:点阵和矢量。对于一个字,点阵字体保存的是每个点的渲染信息。这个方式的劣势在于保存的数据量非常大,并且对放大缩小等操作支持不好。因此出现了矢量字体。对于一个字,矢量字体保存的是字的绘制公式。这个绘制公式包括了字体轮廓(outline)和字体精调(hint)。字体轮廓使用贝塞尔曲线来绘制出字的外部线条。在大分辨率的情况下就需要对字体进行精调了。这个绘制字的公式就叫做字体数据(glyph)。在字体文件中,每个字对应一个glyph。那么字体文件中就存在一个字符映射表(charmap)。

    对于矢量字体,其中用的最为广泛的是TrueType。它的扩展名一般为otf或者ttf。在windows,linux,osx上都得到广泛支持。我们平时看到的.ttf和.ttc的字体文件就是TrueType字体。其中ttc是多个ttf的集合文件(collection)。

    步骤

    TrueType只是一个字体,而要让这个字体在屏幕上显示,就需要字体驱动库了。其中FreeType就是这么一种高效的字体驱动引擎。一个汉字从字体到显示FreeType大致有几个步骤:

    加载字体

    设置字体大小

    加载glyph

    字体对应大小等转换

    绘制字体

    这里特别注意的是FreeType并不只能驱动TrueType字体,它还可以驱动其他各种矢量字体,甚至也可以驱动点阵字体。

    freetype-go

    所以freetype-go就是用go语言实现了FreeType驱动。

    This is an implementation of the Freetype font engine in the Go programming language.

    代码示例:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    // 画一个带有text的图片
    func (this *Signer) drawStringImage(text string) (image.Image, error) {
        fontBytes, err := ioutil.ReadFile(this.fontPath)
        if err != nil {
            return nil, err
        }
     
        font, err := freetype.ParseFont(fontBytes)
        if err != nil {
            return nil, err
        }
     
        fg, bg :=  image.White, image.Black
        rgba := image.NewRGBA(image.Rect(0, 0, 900, 900))
        draw.Draw(rgba, rgba.Bounds(), bg, image.ZP, draw.Src)
     
        c := freetype.NewContext()
        c.SetDPI(this.Dpi)
        c.SetFont(font)
        c.SetFontSize(this.FontSize)
        c.SetClip(rgba.Bounds())
        c.SetDst(rgba)
        c.SetSrc(fg)
     
        // Draw the text.
        pt := freetype.Pt(10, 10+int(c.PointToFix32(12)>>8))
        for _, s := range strings.Split(text, "\r\n") {
            _, err = c.DrawString(s, pt)
            pt.Y += c.PointToFix32(12 * 1.5)
        }
     
        return rgba, nil
    }

    参考文档:

    http://blog.csdn.net/absurd/article/details/1354499

    https://developer.apple.com/fonts/TTRefMan/

    http://www.microsoft.com/typography/otspec/otff.htm

    Creative Commons License

    本文基于署名-非商业性使用 3.0许可协议发布,欢迎转载,演绎,但是必须保留本文的署名叶剑峰(包含链接http://www.cnblogs.com/yjf512/),且不得用于商业目的。如您有任何疑问或者授权方面的协商,请与我联系

     
    分类: Go
  • 相关阅读:
    如何安装unidac 6.2.8 到delphi 7
    Sqoop
    Spark-PySpark sql各种内置函数
    Spark译文(三)
    Spark译文(二)
    Spark译文(一)
    YARN详解
    Spark2.X管理与开发
    Hadoop2.X管理与开发
    离线综合案例
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/3027261.html
Copyright © 2020-2023  润新知