我试图在golang项目中使用freetype / truetype在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行),但这并不能使我在所有字形之间保持一致的结果.
根据Simon的建议,正确的解决方案是使用AdvanceWidth:
原文链接:https://www.f2er.com/go/186965.html粗体示例:
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,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,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.") }