/
font.go
93 lines (80 loc) · 2.32 KB
/
font.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Copyright 2014 Hajime Hoshi
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package blocks
import (
"image/color"
"log"
"strings"
"github.com/golang/freetype/truetype"
"golang.org/x/image/font"
"github.com/hajimehoshi/ebiten"
"github.com/hajimehoshi/ebiten/examples/resources/fonts"
"github.com/hajimehoshi/ebiten/text"
)
const (
arcadeFontBaseSize = 8
)
var (
arcadeFonts map[int]font.Face
)
func getArcadeFonts(scale int) font.Face {
if arcadeFonts == nil {
tt, err := truetype.Parse(fonts.ArcadeN_ttf)
if err != nil {
log.Fatal(err)
}
arcadeFonts = map[int]font.Face{}
for i := 1; i <= 4; i++ {
const dpi = 72
arcadeFonts[i] = truetype.NewFace(tt, &truetype.Options{
Size: float64(arcadeFontBaseSize * i),
DPI: dpi,
Hinting: font.HintingFull,
})
}
}
return arcadeFonts[scale]
}
func textWidth(str string) int {
maxW := 0
for _, line := range strings.Split(str, "\n") {
b, _ := font.BoundString(getArcadeFonts(1), line)
w := (b.Max.X - b.Min.X).Ceil()
if maxW < w {
maxW = w
}
}
return maxW
}
var (
shadowColor = color.NRGBA{0, 0, 0, 0x80}
)
func drawTextWithShadow(rt *ebiten.Image, str string, x, y, scale int, clr color.Color) {
offsetY := arcadeFontBaseSize * scale
for _, line := range strings.Split(str, "\n") {
y += offsetY
text.Draw(rt, line, getArcadeFonts(scale), x+1, y+1, shadowColor)
text.Draw(rt, line, getArcadeFonts(scale), x, y, clr)
}
}
func drawTextWithShadowCenter(rt *ebiten.Image, str string, x, y, scale int, clr color.Color, width int) {
w := textWidth(str) * scale
x += (width - w) / 2
drawTextWithShadow(rt, str, x, y, scale, clr)
}
func drawTextWithShadowRight(rt *ebiten.Image, str string, x, y, scale int, clr color.Color, width int) {
w := textWidth(str) * scale
x += width - w
drawTextWithShadow(rt, str, x, y, scale, clr)
}