之前介绍过使用 FreeType-go 来绘制字(http://www.cnblogs.com/ghj1976/p/3445568.html),  现在相关的包被做了整合,主要是整合到了 github.com/golang/freetype 和 golang.org/x/image/font 这里了,所以就有了这篇博客。

 

例子代码在: https://github.com/golang/freetype/blob/master/example/freetype/main.go

 

package main

import (
    "bufio"
    "flag"
    "fmt"
    "image"
    "image/color"
    "image/draw"
    "image/png"
    "io/ioutil"
    "log"
    "os"

    "github.com/golang/freetype"
    "golang.org/x/image/font"
)

var (
    dpi      = flag.Float64("dpi", 72, "screen resolution in Dots Per Inch")
    fontfile = flag.String("fontfile", "../../testdata/luxisr.ttf", "filename of the ttf font")
    hinting  = flag.String("hinting", "none", "none | full")
    size     = flag.Float64("size", 12, "font size in points")
    spacing  = flag.Float64("spacing", 1.5, "line spacing (e.g. 2 means double spaced)")
    wonb     = flag.Bool("whiteonblack", false, "white text on a black background")
)

var text = []string{
    "’Twas brillig, and the slithy toves",
    "测试中文字 ……&^_^",
    "Did gyre and gimble in the wabe;",
    "All mimsy were the borogoves,",
    "And the mome raths outgrabe.",
    "",
    "“Beware the Jabberwock, my son!",
    "The jaws that bite, the claws that catch!",
    "Beware the Jubjub bird, and shun",
    "The frumious Bandersnatch!”",
    "",
    "He took his vorpal sword in hand:",
    "Long time the manxome foe he sought—",
    "So rested he by the Tumtum tree,",
    "And stood awhile in thought.",
    "",
    "And as in uffish thought he stood,",
    "The Jabberwock, with eyes of flame,",
    "Came whiffling through the tulgey wood,",
    "And burbled as it came!",
    "",
    "One, two! One, two! and through and through",
    "The vorpal blade went snicker-snack!",
    "He left it dead, and with its head",
    "He went galumphing back.",
    "",
    "“And hast thou slain the Jabberwock?",
    "Come to my arms, my beamish boy!",
    "O frabjous day! Callooh! Callay!”",
    "He chortled in his joy.",
    "",
    "’Twas brillig, and the slithy toves",
    "Did gyre and gimble in the wabe;",
    "All mimsy were the borogoves,",
    "And the mome raths outgrabe.",
}

func main() {
    flag.Parse()

    // Read the font data.
    fontBytes, err := ioutil.ReadFile(*fontfile)
    if err != nil {
        log.Println(err)
        return
    }
    f, err := freetype.ParseFont(fontBytes)
    if err != nil {
        log.Println(err)
        return
    }

    // Initialize the context.
    fg, bg := image.Black, image.White
    ruler := color.RGBA{0xdd, 0xdd, 0xdd, 0xff}
    if *wonb {
        fg, bg = image.White, image.Black
        ruler = color.RGBA{0x22, 0x22, 0x22, 0xff}
    }
    rgba := image.NewRGBA(image.Rect(0, 0, 640, 480))
    draw.Draw(rgba, rgba.Bounds(), bg, image.ZP, draw.Src)
    c := freetype.NewContext()
    c.SetDPI(*dpi)
    c.SetFont(f)
    c.SetFontSize(*size)
    c.SetClip(rgba.Bounds())
    c.SetDst(rgba)
    c.SetSrc(fg)
    switch *hinting {
    default:
        c.SetHinting(font.HintingNone)
    case "full":
        c.SetHinting(font.HintingFull)
    }

    // Draw the guidelines.
    for i := 0; i < 200; i++ {
        rgba.Set(10, 10+i, ruler)
        rgba.Set(10+i, 10, ruler)
    }

    // Draw the text.
    pt := freetype.Pt(10, 10+int(c.PointToFixed(*size)>>6))
    for _, s := range text {
        _, err = c.DrawString(s, pt)
        if err != nil {
            log.Println(err)
            return
        }
        pt.Y += c.PointToFixed(*size * *spacing)
    }

    // Save that RGBA image to disk.
    outFile, err := os.Create("out.png")
    if err != nil {
        log.Println(err)
        os.Exit(1)
    }
    defer outFile.Close()
    b := bufio.NewWriter(outFile)
    err = png.Encode(b, rgba)
    if err != nil {
        log.Println(err)
        os.Exit(1)
    }
    err = b.Flush()
    if err != nil {
        log.Println(err)
        os.Exit(1)
    }
    fmt.Println("Wrote out.png OK.")
}

执行效果如下:

./testFont2 -fontfile="字体管家淘淘体.ttf"

执行效果:

./testFont2 -fontfile="6f14c8f349377d5ebe2b0a5e2851a6f6.ttf"

执行效果:

./testFont2 -fontfile="Sliced by Hand.ttf"

执行效果,这个字体不支持中文,就会出现下面情况:

 

 

 

一些免费的字体库下载

英文字体库

http://www.freefontspro.com/cn/

http://cn.fontriver.com/ 

中文字体库

http://fonts.mobanwang.com/ 

http://www.touwenzi.com/

Golang 图片上绘制文字的更多相关文章

  1. Android 使用Canvas在图片上绘制文字

    一个小应用,在图片上绘制文字,以下是绘制文字的方法,并且能够实现自动换行,字体自动适配屏幕大小 private void drawNewBitmap(ImageView imageView, Stri ...

  2. C#实现图片叠加,图片上嵌入文字,文字生成图片的方法

    /// <summary>     /// 图片叠加     /// </summary>     /// <param name="sender"& ...

  3. C# 在Bitmap上绘制文字出现锯齿的问题

    解决锯齿问题主要是修改Graphics的属性 修复绘制图片锯齿问题可以修改 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiA ...

  4. 图像处理---《在图片上打印文字 putText()》

    图像处理---<在图片上打印文字 putText()> 目的:想在处理之后的图像上打印输出结果. 方法: (1)只在图像上打印 数字.字母的话:                 1.Mat ...

  5. python如何在图片上添加文字(中文和英文)

    Python在图片上添加文字的两种方法:OpenCV和PIL 一.OpenCV方法 1.安装cv2 pip install opencv-python 2.利用putText方法来实现在图片的指定位置 ...

  6. C#图像处理(1):在图片上加文字和改变文字的方向

    C#在图片上加文字,代码如下: /// <summary> /// 图片上方加文字,文字将会被180度反转 /// </summary> /// <param name= ...

  7. python 图片上添加文字

    import PIL from PIL import ImageFont from PIL import Image from PIL import ImageDraw #设置字体,如果没有,也可以不 ...

  8. 使用Qpaint在图片上写文字

    开发过程中需要实现在图片上叠加文字,可以采用Qpaint在图片上写文字,然后将图片显示在上面.再将Qlabel加到Qwidget中.效果如下 //创建对象,加载图片 QPixmap pix; pix. ...

  9. 函数putText()在图片上写文字

    #include <iostream> #include <opencv2/opencv.hpp> using namespace std; using namespace c ...

随机推荐

  1. linux服务之rsync

    http://www.cnblogs.com/itech/archive/2010/06/13/1757952.html rsync与mfs好像有点类似,都是传输块的chunk,chunk的 1)软件 ...

  2. Windows Service Wrapper

    This project creates a wrapper executable that can be used to host any executable as an Windows serv ...

  3. windows系统安装MongoDB

    最近一直在学习node.js,nodejs开发指南中有一个微博的web开发项目,由于该书出的比较早(2012出的),目前为止利用nodejs进行web开发各种组合技术都发生了很大的更新,例如书中选择的 ...

  4. Javascript 错误捕获

    一.一般写JS代码很少捕获异常,建议捕获异常,具体代码如下: 1.写法一: try { //具体代码 } catch(error) { alert("Error:" + error ...

  5. 查看SQL执行计划

    一用户进入某界面慢得要死,查看SQL执行计划如下(具体SQL语句就不完全公布了,截断的如下): call     count       cpu    elapsed       disk       ...

  6. Python基础教程【读书笔记】 - 2016/7/31

    希望通过博客园持续的更新,分享和记录Python基础知识到高级应用的点点滴滴! 第十波:第10章  充电时刻 Python语言的核心非常强大,同时还提供了更多值得一试的工具.Python的标准安装包括 ...

  7. IntelliJ IDEA使用SSH功能

    Tools→Start SSH session... 选择Edit credentials... 输入SSH登录信息即可 输入SSH登录信息,Port默认为22 来自为知笔记(Wiz)

  8. Python标准库

    Python标准库是随Python附带安装的,它包含大量极其有用的模块.熟悉Python标准库是十分重要的,因为如果你熟悉这些库中的模块,那么你的大多数问题都可以简单快捷地使用它们来解决. sys模块 ...

  9. golang rbac框架

    在 https://github.com/mikespook/gorbac/tree/v1.0 github上新的版本是开发板,得用这里的老版 demo package main import ( & ...

  10. centos 连不上网

    ifc-eth0 里面要加DNS1=192.168.1.1 一定是DNS1这样的,不要是DNS