tins2020/fonts.go

90 lines
1.7 KiB
Go
Raw Normal View History

2020-05-08 16:38:26 +00:00
package tins2020
import (
2020-05-09 13:32:43 +00:00
"fmt"
"github.com/veandco/go-sdl2/sdl"
2020-05-08 16:38:26 +00:00
"github.com/veandco/go-sdl2/ttf"
"opslag.de/schobers/fs/vfs"
)
type Font struct {
*ttf.Font
}
func (f *Font) Render(renderer *sdl.Renderer, text string, pos Point, color sdl.Color) (*Texture, error) {
surface, err := f.RenderUTF8Solid(text, color)
if err != nil {
return nil, err
}
defer surface.Free()
texture, err := NewTextureFromSurface(renderer, surface)
if err != nil {
return nil, err
}
return texture, nil
}
func (f *Font) RenderCopy(renderer *sdl.Renderer, text string, pos Point, color sdl.Color) error {
texture, err := f.Render(renderer, text, pos, color)
if err != nil {
return err
}
defer texture.Destroy()
texture.Copy(renderer, texture.RectOffset(pos))
return nil
}
2020-05-08 16:38:26 +00:00
type Fonts struct {
dir vfs.CopyDir
fonts map[string]*Font
2020-05-08 16:38:26 +00:00
}
func (f *Fonts) Init(dir vfs.CopyDir) {
f.dir = dir
f.fonts = map[string]*Font{}
2020-05-08 16:38:26 +00:00
}
func (f *Fonts) Font(name string) *Font { return f.fonts[name] }
2020-05-09 13:32:43 +00:00
type FontDescriptor struct {
Name string
Path string
Size int
}
func (f *Fonts) LoadDesc(fonts ...FontDescriptor) error {
for _, desc := range fonts {
err := f.Load(desc.Name, desc.Path, desc.Size)
if err != nil {
return fmt.Errorf("error loading '%s'; error: %v", desc.Name, err)
}
}
return nil
}
2020-05-08 16:38:26 +00:00
func (f *Fonts) Load(name, path string, size int) error {
fontPath, err := f.dir.Retrieve(path)
if err != nil {
return err
}
font, err := ttf.OpenFont(fontPath, size)
if err != nil {
return err
}
if font, ok := f.fonts[name]; ok {
font.Close()
}
f.fonts[name] = &Font{font}
2020-05-08 16:38:26 +00:00
return nil
}
func (f *Fonts) Destroy() {
if f.fonts == nil {
return
}
for _, f := range f.fonts {
f.Close()
}
}