From e82fe34a2b8ba38644a541a05cb1fb9f5e122157 Mon Sep 17 00:00:00 2001 From: darcy Date: Thu, 19 May 2022 21:58:08 +0800 Subject: [PATCH] docs: add example of using chinese --- README_zh.md | 4 +++- examples/basic/chinese.go | 50 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 examples/basic/chinese.go diff --git a/README_zh.md b/README_zh.md index 57d9db4..1589923 100644 --- a/README_zh.md +++ b/README_zh.md @@ -220,4 +220,6 @@ BenchmarkMultiChartSVGRender-8 367 3356325 ns/op 默认使用的字符为`roboto`为英文字体库,因此如果需要显示中文字符需要增加中文字体库,`InstallFont`函数可添加对应的字体库,成功添加之后则指定`title.textStyle.fontFamily`即可。 在浏览器中使用`svg`时,如果指定的`fontFamily`不支持中文字符,展示的中文并不会乱码,但是会导致在计算字符宽度等错误。 -[中文字库noto-cjk](https://github.com/googlefonts/noto-cjk) \ No newline at end of file +字体文件可以在[中文字库noto-cjk](https://github.com/googlefonts/noto-cjk)下载,注意下载时选择字体格式为 `ttf` 格式,如果选用 `otf` 格式可能会加载失败。 + +示例见 [examples/basic/chinese.go](examples/basic/chinese.go) \ No newline at end of file diff --git a/examples/basic/chinese.go b/examples/basic/chinese.go new file mode 100644 index 0000000..4380349 --- /dev/null +++ b/examples/basic/chinese.go @@ -0,0 +1,50 @@ +package main + +import ( + "log" + "os" + + charts "github.com/vicanso/go-charts" +) + +func echartsRender() ([]byte, error) { + return charts.RenderEChartsToPNG(`{ + "title": { + "text": "用户访问次数", + "textStyle": { + "fontFamily": "chinese" + } + }, + "xAxis": { + "data": ["周一", "周二", "周三", "周四", "周五", "周六", "周日"] + }, + "series": [ + { + "data": [150, 230, 224, 218, 135, 147, 260], + "label": { + "show": true + } + } + ] + }`) +} + +func main() { + fontData, err := os.ReadFile("/Users/darcy/Downloads/NotoSansCJKsc-VF.ttf") + if err != nil { + log.Fatalln("Error when reading font file:", err) + } + + if err := charts.InstallFont("chinese", fontData); err != nil { + log.Fatalln("Error when instaling font:", err) + } + + fileData, err := echartsRender() + + if err != nil { + log.Fatalln("Error when rendering image:", err) + } + if err := os.WriteFile("chinese.png", fileData, 0644); err != nil { + log.Fatalln("Error when save image to chinese.png:", err) + } +}