Fyne设置中文,解决中文乱码

1,328 阅读1分钟

Fyne默认不支持中文 image.png 解决: 先安装go-findfont 地址github.com/flopp/go-fi…,控制台执行

go get -u github.com/flopp/go-findfont 粘贴这段代码

func init() {
   fontPath, err := findfont.Find("喜欢的字体")
   if err != nil {
      panic(err)
   }
   fmt.Printf("Found 'arial.ttf' in '%s'\n", fontPath)

   // load the font with the freetype library
   // 原作者使用的ioutil.ReadFile已经弃用
   fontData, err := os.ReadFile(fontPath)
   if err != nil {
      panic(err)
   }
   _, err = truetype.Parse(fontData)
   if err != nil {
      panic(err)
   }
   os.Setenv("FYNE_FONT", fontPath)
}

到项目根目录下新建一个文件夹用来存放字体文件 如 image.png

Windows电脑搜索C:\Windows\Fonts image.png 找到喜欢的字体复制粘贴到新建的文件夹 替换"喜欢的字体"为文件名

image.png 测试

func main() {
   // use the font...
   MyApp := app.New()
   c := MyApp.NewWindow("fyne支持中文")
   labels := widget.NewLabel("中文看看行不行")
   c.SetContent(labels)
   c.Resize(fyne.NewSize(600, 600))
   c.ShowAndRun()
}

结果 image.png