ebiten/examples/blocks/blocks/font.go
Hajime Hoshi d8ba49eaab examples/blocks: Fix initializing fonts not to depend on init() order
https://golang.org/ref/spec#Package_initialization
It is expected that init() is executed in file name order,
but this is not 100%.
2018-03-17 01:56:32 +09:00

87 lines
2.2 KiB
Go

// 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 {
b, _ := font.BoundString(getArcadeFonts(1), str)
return (b.Max.X - b.Min.X).Ceil()
}
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)
}