package imglib import ( "fmt" "os" "runtime" "sync" "github.com/golang/freetype/truetype" ) var ( fontCacheOnce sync.Once cachedFont *truetype.Font cachedFontErr error ) // GetFont 获取系统默认中文字体(全局缓存,仅首次加载时读取磁盘) func GetFont() (*truetype.Font, error) { fontCacheOnce.Do(func() { path := getDefaultFontPath() if path == "" { cachedFontErr = fmt.Errorf("未找到系统字体文件") return } data, err := os.ReadFile(path) if err != nil { cachedFontErr = fmt.Errorf("读取字体文件失败: %v", err) return } cachedFont, cachedFontErr = truetype.Parse(data) }) return cachedFont, cachedFontErr } func getDefaultFontPath() string { switch runtime.GOOS { case "windows": paths := []string{ "C:/Windows/Fonts/simhei.ttf", "C:/Windows/Fonts/simsun.ttc", "C:/Windows/Fonts/msyh.ttc", } for _, p := range paths { if _, err := os.Stat(p); err == nil { return p } } case "darwin": return "/System/Library/Fonts/PingFang.ttc" case "linux": paths := []string{ "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc", "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", } for _, p := range paths { if _, err := os.Stat(p); err == nil { return p } } } return "" }