diff --git a/canvas.go b/canvas.go index 92aa5e2..68ba849 100644 --- a/canvas.go +++ b/canvas.go @@ -442,20 +442,28 @@ func (cv *Canvas) SetLineWidth(width float64) { cv.state.lineWidth = width } -// SetFont sets the font and font size +// SetFont sets the font and font size. The font parameter can be: +// - a font loaded with the LoadFont function +// - a string matching the name parameter on LoadFont +// - a filename for a font to load which will be cached +// - nil, in which case the first loaded font will be used func (cv *Canvas) SetFont(font interface{}, size float64) { - switch v := font.(type) { - case *Font: - cv.state.font = v - case *truetype.Font: - cv.state.font = &Font{font: v} - case string: - if f, ok := fonts[v]; ok { - cv.state.font = f - } else { - f, err := LoadFont(v, v) - if err == nil { + if font == nil { + cv.state.font = defaultFont + } else { + switch v := font.(type) { + case *Font: + cv.state.font = v + case *truetype.Font: + cv.state.font = &Font{font: v} + case string: + if f, ok := fonts[v]; ok { cv.state.font = f + } else { + f, err := LoadFont(v, v) + if err == nil { + cv.state.font = f + } } } } diff --git a/text.go b/text.go index 0e94047..097e5f2 100644 --- a/text.go +++ b/text.go @@ -20,6 +20,8 @@ type Font struct { var fonts = make(map[string]*Font) var zeroes [alphaTexSize]byte +var defaultFont *Font + func LoadFont(src interface{}, name string) (*Font, error) { var f *Font switch v := src.(type) { @@ -47,12 +49,19 @@ func LoadFont(src interface{}, name string) (*Font, error) { if name != "" { fonts[name] = f } + if defaultFont == nil { + defaultFont = f + } return f, nil } func (cv *Canvas) FillText(str string, x, y float64) { cv.activate() + if cv.state.font == nil { + return + } + frc := fontRenderingContext frc.setFont(cv.state.font.font) frc.setFontSize(float64(cv.state.fontSize)) @@ -129,6 +138,10 @@ type TextMetrics struct { } func (cv *Canvas) MeasureText(str string) TextMetrics { + if cv.state.font == nil { + return TextMetrics{} + } + frc := fontRenderingContext frc.setFont(cv.state.font.font) frc.setFontSize(float64(cv.state.fontSize))