go - 使用 Truetype 对齐 golang 中的文本

标签 go truetype

我正在尝试使用 freetype/truetype 在 Golang 项目中的 png 上呈现一些文本。正如您从附件中看到的那样,我试图在列中呈现 4 个字母 - 每个字母在列中居中。已使用 truetype api 来获取字形的边界和宽度,但无法转换这些来为每个字形提供准确的偏移量。例如使用 O 字形,给定我使用的字体。我得到以下尺寸:

Hmetric {AdvanceWidth:543 LeftSideBearing:36} 界限 {XMin:0 YMin:-64 XMax:512 YMax:704} 前进宽度:512

最后一个维度从 GlyphBuf 返回.

我使用以下内容渲染它:

大小:= 125.00 tileOffset := (int(tileWidth) * i) + int(tileWidth/2) pt := freetype.Pt(tileOffset, (imgH-newCharHeight)-int(size))

如何使用 truetype 返回的字形尺寸来正确偏移字母?我试过使用 AdvanceWidth 详细的in this plotinum代码(第 160 行),但这并不能在所有字形中为我提供一致的结果。

Example of rendering

最佳答案

根据 Simon 的建议,正确的解决方案是使用 AdvanceWidth:

enter image description here

粗略的例子:

package main

import (
    "flag"
    "fmt"
    "io/ioutil"
    "log"
    "image"
    "bufio"
    "image/draw"
    "image/png"
    "image/color"
    "github.com/golang/freetype/truetype"
    "golang.org/x/image/font"
    "github.com/golang/freetype"
    "os"
)

var (
    dpi      = flag.Float64("dpi", 72, "screen resolution in Dots Per Inch")
    fontfile = flag.String("fontfile", "/usr/share/fonts/liberation/LiberationSerif-Regular.ttf", "filename of the ttf font")
    hinting  = flag.String("hinting", "none", "none | full")
    size     = flag.Float64("size", 125, "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")
    text     = string("JOJO")
)


func main() {
    flag.Parse()
    fmt.Printf("Loading fontfile %q\n", *fontfile)
    b, err := ioutil.ReadFile(*fontfile)
    if err != nil {
        log.Println(err)
        return
    }
    f, err := truetype.Parse(b)
    if err != nil {
        log.Println(err)
        return
    }

    // Freetype context
    fg, bg := image.Black, image.White
    rgba := image.NewRGBA(image.Rect(0, 0, 1000, 200))
    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)
    }

    // Make some background

    // Draw the guidelines.
    ruler := color.RGBA{0xdd, 0xdd, 0xdd, 0xff}
    for rcount := 0; rcount < 4; rcount ++ {
        for i := 0; i < 200; i++ {
            rgba.Set(250*rcount, i, ruler)
        }
    }

    // Truetype stuff
    opts := truetype.Options{}
    opts.Size = 125.0
    face := truetype.NewFace(f, &opts)


    // Calculate the widths and print to image
    for i, x := range(text) {
        awidth, ok := face.GlyphAdvance(rune(x))
        if ok != true {
            log.Println(err)
            return
        }
        iwidthf := int(float64(awidth) / 64)
        fmt.Printf("%+v\n", iwidthf)

        pt := freetype.Pt(i*250+(125-iwidthf/2), 128)
        c.DrawString(string(x), pt)
        fmt.Printf("%+v\n", awidth)
    }


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


}

关于go - 使用 Truetype 对齐 golang 中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29105540/

相关文章:

css - 合并 Flaticon 集合/同时使用多个集合

go - 如何获取空闲 inode 数量? (`df -i` 等效)

windows - 在Win7中,某些字体不能像在Win2K/XP中那样工作

image - 从ttf文件中提取字体字符图像

mysql - Go 的连续 MySQL 查询在某个时间点后变得更慢

PDF 文本提取问题 - 字体/大小写不一致

java - 在客户端安装.ttf文件

android - 如何使用 gomobile 将多个包绑定(bind)到单个 Java AAR 文件中?

go - Android Things 是否支持 golang?

regex - 使用正则表达式检查URL是否在句子中