feat: support get and set default font

This commit is contained in:
vicanso 2022-11-12 20:01:36 +08:00
parent 2ed86a81d0
commit de4250f60b
6 changed files with 24 additions and 10 deletions

View file

@ -26,7 +26,6 @@ import (
"sort"
"github.com/golang/freetype/truetype"
"github.com/wcharczuk/go-chart/v2"
)
type ChartOption struct {
@ -270,7 +269,7 @@ func (o *ChartOption) fillDefault() {
o.font, _ = GetFont(o.FontFamily)
if o.font == nil {
o.font, _ = chart.GetDefaultFont()
o.font, _ = GetDefaultFont()
} else {
// 如果指定了字体,则设置主题的字体
t.SetFont(o.font)
@ -388,7 +387,7 @@ func TableOptionRender(opt TableChartOption) (*Painter, error) {
opt.Font, _ = GetFont(opt.FontFamily)
}
if opt.Font == nil {
opt.Font, _ = chart.GetDefaultFont()
opt.Font, _ = GetDefaultFont()
}
p, err := NewPainter(PainterOptions{

19
font.go
View file

@ -32,9 +32,13 @@ import (
var fonts = sync.Map{}
var ErrFontNotExists = errors.New("font is not exists")
var defaultFontFamily = "defaultFontFamily"
func init() {
_ = InstallFont("roboto", roboto.Roboto)
name := "roboto"
_ = InstallFont(name, roboto.Roboto)
font, _ := GetFont(name)
SetDefaultFont(font)
}
// InstallFont installs the font for charts
@ -47,6 +51,19 @@ func InstallFont(fontFamily string, data []byte) error {
return nil
}
// GetDefaultFont get default font
func GetDefaultFont() (*truetype.Font, error) {
return GetFont(defaultFontFamily)
}
// SetDefaultFont set default font
func SetDefaultFont(font *truetype.Font) {
if font == nil {
return
}
fonts.Store(defaultFontFamily, font)
}
// GetFont get the font by font family
func GetFont(fontFamily string) (*truetype.Font, error) {
value, ok := fonts.Load(fontFamily)

View file

@ -24,7 +24,6 @@ package charts
import (
"github.com/golang/freetype/truetype"
"github.com/wcharczuk/go-chart/v2"
)
// NewMarkLine returns a series mark line
@ -75,7 +74,7 @@ func (m *markLinePainter) Render() (Box, error) {
}
font := opt.Font
if font == nil {
font, _ = chart.GetDefaultFont()
font, _ = GetDefaultFont()
}
summary := s.Summary()
for _, markLine := range s.MarkLine.Data {

View file

@ -149,7 +149,7 @@ func NewPainter(opts PainterOptions, opt ...PainterOption) (*Painter, error) {
}
font := opts.Font
if font == nil {
f, err := chart.GetDefaultFont()
f, err := GetDefaultFont()
if err != nil {
return nil, err
}

View file

@ -351,7 +351,7 @@ func TestPainterTextFit(t *testing.T) {
Type: ChartOutputSVG,
})
assert.Nil(err)
f, _ := chart.GetDefaultFont()
f, _ := GetDefaultFont()
style := Style{
FontSize: 12,
FontColor: chart.ColorBlack,

View file

@ -24,7 +24,6 @@ package charts
import (
"github.com/golang/freetype/truetype"
"github.com/wcharczuk/go-chart/v2"
"github.com/wcharczuk/go-chart/v2/drawing"
)
@ -311,7 +310,7 @@ func (t *themeColorPalette) GetFont() *truetype.Font {
if t.font != nil {
return t.font
}
f, _ := chart.GetDefaultFont()
f, _ := GetDefaultFont()
return f
}