diff --git a/README_zh.md b/README_zh.md index 57d9db4..2d16b04 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/chinese/main.go](examples/chinese/main.go) \ No newline at end of file diff --git a/assets/go-charts.png b/assets/go-charts.png index 5ead961..a80e241 100644 Binary files a/assets/go-charts.png and b/assets/go-charts.png differ diff --git a/axis.go b/axis.go index 7b828d2..aa7cf7d 100644 --- a/axis.go +++ b/axis.go @@ -91,6 +91,9 @@ func (a *axisPainter) Render() (Box, error) { } font := opt.Font + if font == nil { + font = a.p.font + } if font == nil { font = theme.GetFont() } diff --git a/charts.go b/charts.go index 5759367..cd1ac2b 100644 --- a/charts.go +++ b/charts.go @@ -252,6 +252,7 @@ func Render(opt ChartOption, opts ...OptionFunc) (*Painter, error) { Type: opt.Type, Width: opt.Width, Height: opt.Height, + Font: opt.font, }) if err != nil { return nil, err diff --git a/examples/chinese/main.go b/examples/chinese/main.go new file mode 100644 index 0000000..13724aa --- /dev/null +++ b/examples/chinese/main.go @@ -0,0 +1,118 @@ +package main + +import ( + "io/ioutil" + "os" + "path/filepath" + + "github.com/vicanso/go-charts" +) + +func writeFile(buf []byte) error { + tmpPath := "./tmp" + err := os.MkdirAll(tmpPath, 0700) + if err != nil { + return err + } + + file := filepath.Join(tmpPath, "chinese-line-chart.png") + err = ioutil.WriteFile(file, buf, 0600) + if err != nil { + return err + } + return nil +} + +func main() { + // 字体文件需要自行下载 + buf, err := ioutil.ReadFile("../NotoSansSC.ttf") + if err != nil { + panic(err) + } + err = charts.InstallFont("noto", buf) + if err != nil { + panic(err) + } + + values := [][]float64{ + { + 120, + 132, + 101, + 134, + 90, + 230, + 210, + }, + { + 220, + 182, + 191, + 234, + 290, + 330, + 310, + }, + { + 150, + 232, + 201, + 154, + 190, + 330, + 410, + }, + { + 320, + 332, + 301, + 334, + 390, + 330, + 320, + }, + { + 820, + 932, + 901, + 934, + 1290, + 1330, + 1320, + }, + } + p, err := charts.LineRender( + values, + charts.TitleTextOptionFunc("Line"), + charts.FontFamilyOptionFunc("noto"), + charts.XAxisDataOptionFunc([]string{ + "星期一", + "星期二", + "星期三", + "星期四", + "星期五", + "星期六", + "星期日", + }), + charts.LegendLabelsOptionFunc([]string{ + "邮件", + "广告", + "视频广告", + "直接访问", + "搜索引擎", + }, charts.PositionCenter), + ) + + if err != nil { + panic(err) + } + + buf, err = p.Bytes() + if err != nil { + panic(err) + } + err = writeFile(buf) + if err != nil { + panic(err) + } +}