text/v2: let NewMultiFace return an error

Updates #2845
This commit is contained in:
Hajime Hoshi 2023-12-04 01:16:39 +09:00
parent fa3ec12731
commit 81e0e61a43
3 changed files with 25 additions and 4 deletions

View File

@ -74,7 +74,11 @@ func (g *Game) Update() error {
Size: 32, Size: 32,
} }
g.face = text.NewMultiFace(en, ja) f, err := text.NewMultiFace(en, ja)
if err != nil {
return err
}
g.face = f
} }
return nil return nil
} }

View File

@ -15,6 +15,7 @@
package text package text
import ( import (
"errors"
"unicode/utf8" "unicode/utf8"
"github.com/hajimehoshi/ebiten/v2/vector" "github.com/hajimehoshi/ebiten/v2/vector"
@ -31,11 +32,24 @@ type MultiFace struct {
} }
// NewMultiFace creates a new MultiFace from the given faces. // NewMultiFace creates a new MultiFace from the given faces.
func NewMultiFace(faces ...Face) *MultiFace { //
// NewMultiFace returns an error when no faces are given, or the faces' directions don't agree.
func NewMultiFace(faces ...Face) (*MultiFace, error) {
if len(faces) == 0 {
return nil, errors.New("text: no faces are given at NewMultiFace")
}
d := faces[0].direction()
for _, f := range faces[1:] {
if f.direction() != d {
return nil, errors.New("text: all the faces' directions must agree")
}
}
m := &MultiFace{} m := &MultiFace{}
m.faces = make([]Face, len(faces)) m.faces = make([]Face, len(faces))
copy(m.faces, faces) copy(m.faces, faces)
return m return m, nil
} }
// Metrics implements Face. // Metrics implements Face.

View File

@ -243,7 +243,10 @@ func TestUnhashableFace(t *testing.T) {
func TestMultiFace(t *testing.T) { func TestMultiFace(t *testing.T) {
faces := []text.Face{text.NewStdFace(bitmapfont.Face)} faces := []text.Face{text.NewStdFace(bitmapfont.Face)}
f := text.NewMultiFace(faces...) f, err := text.NewMultiFace(faces...)
if err != nil {
t.Fatal(err)
}
img := ebiten.NewImage(30, 30) img := ebiten.NewImage(30, 30)
text.Draw(img, "Hello", f, nil) text.Draw(img, "Hello", f, nil)