aboutsummaryrefslogtreecommitdiff
path: root/go/ui/button.go
blob: a755c5c083cc588afa76bc4fb42082f47fd16bde (plain)
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
package ui

import (
	"image/color"

	"github.com/hajimehoshi/ebiten/v2"
	"github.com/hajimehoshi/ebiten/v2/text/v2"
	"github.com/hajimehoshi/ebiten/v2/vector"

	"muhq.space/muhqs-game/go/font"
)


type Button interface {
	Widget
	Clickable
}

type SimpleButton struct {
	WidgetBase
	label   string
	OnClick func(b *SimpleButton)
	Bg      color.Color
	Fg      color.Color
	font    *text.GoTextFace
	lineSpacing float64
}

func NewSimpleButton(x, y, w, h int, label string, onClick func(b *SimpleButton)) *SimpleButton {
	sb := &SimpleButton{NewWidgetBase(x, y, w, h), label, onClick, Gray, color.White, font.Font24, 1.5}
	sb.renderImpl = func() *ebiten.Image { return sb.render() }
	return sb
}

func (b *SimpleButton) render() *ebiten.Image {
	img := ebiten.NewImage(b.Width, b.Height)

	vector.DrawFilledRect(img, float32(0), float32(0), float32(b.Width), float32(b.Height), b.Bg, false)

	w, h := text.Measure(b.label, b.font, b.font.Size * b.lineSpacing)
	x := float64(b.Width)/2 - w/2
	y := float64(b.Height)/2 - h/2
	op := &text.DrawOptions{}
	op.GeoM.Translate(x, y)
	op.ColorScale.ScaleWithColor(b.Fg)
	text.Draw(img, b.label, font.Font24, op)
	return img
}

func (b *SimpleButton) Click(x, y int) {
	b.OnClick(b)
}

func (b *SimpleButton) UpdateLabel(label string) {
	if b.label != label {
		b.label = label
		b.ForceRedraw()
	}
}