From 29a1bdc1fb05dc4e8fc9265f1e1321044525f119 Mon Sep 17 00:00:00 2001 From: vicanso Date: Sun, 30 Jan 2022 18:27:18 +0800 Subject: [PATCH] refactor: adjust legend to center as default --- legend.go | 21 +++++++++++++++++++-- line_chart.go | 1 - 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/legend.go b/legend.go index e37baf3..ad9be61 100644 --- a/legend.go +++ b/legend.go @@ -54,6 +54,23 @@ func drawLegend(p *Draw, opt *LegendOption, theme *Theme) (chart.Box, error) { legendDotHeight := 5 textPadding := 5 legendMargin := 10 + + widthCount := 0 + // 文本宽度 + for _, text := range opt.Data { + b := r.MeasureText(text) + widthCount += b.Width() + } + // 加上标记 + widthCount += legendWidth * len(opt.Data) + // 文本的padding + widthCount += 2 * textPadding * len(opt.Data) + // margin的宽度 + widthCount += legendMargin * (len(opt.Data) - 1) + + // TODO 支持更多的定位方式 + // 居中 + x = (legendDraw.Box.Width() - widthCount) >> 1 for index, text := range opt.Data { if index != 0 { x += legendMargin @@ -61,12 +78,12 @@ func drawLegend(p *Draw, opt *LegendOption, theme *Theme) (chart.Box, error) { style := chart.Style{ StrokeColor: theme.GetSeriesColor(index), FillColor: theme.GetSeriesColor(index), - StrokeWidth: 2, + StrokeWidth: 3, } textBox := r.MeasureText(text) renderText := func() { x += textPadding - legendDraw.text(text, x, y+legendDotHeight-1) + legendDraw.text(text, x, y+legendDotHeight-2) x += textBox.Width() x += textPadding } diff --git a/line_chart.go b/line_chart.go index 33e3ffa..391365b 100644 --- a/line_chart.go +++ b/line_chart.go @@ -58,7 +58,6 @@ func NewLineChart(opt LineChartOption) (*Draw, error) { return nil, err } - opt.Legend.Style.Padding.Left += titleBox.Right _, err = drawLegend(d, &opt.Legend, &theme) if err != nil { return nil, err