我們知道,一個.ttf(或otf)字體檔案的檔案名并不總是與字體家族名稱相同,例如,如果我重命名Arial.ttf為abcd.ttf,它的字體家族名稱仍然是Arial,那么golang中是否有一個包或庫來決議.ttf并得到那個名字?
我試過
有幾種方法*truetype.Font
Name 回傳給定 NameID 的字體名稱值
我在哪里可以NameID?

編輯:
原來NameID是一個go常量,代表fieldTrueType字體屬性中的一個,我發現NameIDPostscriptNamefield的值會被用作字體唯一名稱,例如一個.fcpxml檔案會使用這個值作為它的字體名稱
以下代碼段可以獲取.ttf檔案的唯一字體名稱
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
// the original freetype has a bug for utf8: https://github.com/golang/freetype/issues/66
// "github.com/golang/freetype"
// so we use this beta one
"github.com/beta/freetype"
"github.com/beta/freetype/truetype"
)
// getPostscriptName returns the PostscriptName of a .ttf font file
func getPostscriptName(fontFilePath string) (postscriptName string, err error) {
postscriptName = ""
fontBytes, err := ioutil.ReadFile(fontFilePath)
if err == nil {
font, err := freetype.ParseFont(fontBytes)
if err == nil {
postscriptName = font.Name(truetype.NameIDPostscriptName)
}
}
return postscriptName, err
}
func main() {
fontFileRelative := "Downloads/New Folder With Items 5/Arial.ttf"
homeDir, _ := os.UserHomeDir()
fontFile := filepath.Join(homeDir, fontFileRelative)
postscriptName, _ := getPostscriptName(fontFile)
fmt.Println(postscriptName)
}
uj5u.com熱心網友回復:
使用這個 go library freetype可以讀取 ttf 檔案的資料,您只需要提供字體資料,它將決議所有資料。這里還有一篇關于使用 javascipt 手動讀取 ttf 檔案內容的文章。
編輯:如果您使用 freetype 來獲取姓氏或其他資訊,您可以使用結構的 Name reciever 函式,它接受一個 NameId,它是 uint16 的別名。(您可以在名稱 id 代碼部分找到有效值的完整表)
例如,您可以使用以下代碼獲取字體系列名稱:
package main
import (
"fmt"
"io/ioutil"
"github.com/golang/freetype"
)
func main() {
fontFile := "./font.ttf"
fontBytes, err := ioutil.ReadFile(fontFile)
font, err := freetype.ParseFont(fontBytes)
if err == nil {
fmt.Println(font.Name(1))
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/423081.html
標籤:
