refactor: adjust legend to center as default

This commit is contained in:
vicanso 2022-01-30 18:27:18 +08:00
parent c4b5ac3f42
commit 29a1bdc1fb
2 changed files with 19 additions and 3 deletions

View file

@ -54,6 +54,23 @@ func drawLegend(p *Draw, opt *LegendOption, theme *Theme) (chart.Box, error) {
legendDotHeight := 5 legendDotHeight := 5
textPadding := 5 textPadding := 5
legendMargin := 10 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 { for index, text := range opt.Data {
if index != 0 { if index != 0 {
x += legendMargin x += legendMargin
@ -61,12 +78,12 @@ func drawLegend(p *Draw, opt *LegendOption, theme *Theme) (chart.Box, error) {
style := chart.Style{ style := chart.Style{
StrokeColor: theme.GetSeriesColor(index), StrokeColor: theme.GetSeriesColor(index),
FillColor: theme.GetSeriesColor(index), FillColor: theme.GetSeriesColor(index),
StrokeWidth: 2, StrokeWidth: 3,
} }
textBox := r.MeasureText(text) textBox := r.MeasureText(text)
renderText := func() { renderText := func() {
x += textPadding x += textPadding
legendDraw.text(text, x, y+legendDotHeight-1) legendDraw.text(text, x, y+legendDotHeight-2)
x += textBox.Width() x += textBox.Width()
x += textPadding x += textPadding
} }

View file

@ -58,7 +58,6 @@ func NewLineChart(opt LineChartOption) (*Draw, error) {
return nil, err return nil, err
} }
opt.Legend.Style.Padding.Left += titleBox.Right
_, err = drawLegend(d, &opt.Legend, &theme) _, err = drawLegend(d, &opt.Legend, &theme)
if err != nil { if err != nil {
return nil, err return nil, err