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

import (
	"image/color"

	"github.com/hajimehoshi/ebiten/v2"
	"github.com/hajimehoshi/ebiten/v2/ebitenutil"
	"github.com/hajimehoshi/ebiten/v2/text"
)

type Button interface {
	Widget
	Contains(x, y int) bool
	Click(x, y int)
}

type SimpleButton struct {
	X, Y          int
	Width, Height int
	img           *ebiten.Image
	OnClick       func(b *SimpleButton)
}

func NewSimpleButton(x, y, w, h int, onClick func(b *SimpleButton), label string) *SimpleButton {
	img := ebiten.NewImage(w, h)

	// b := text.BoundString(f, label)
	ebitenutil.DrawRect(img, float64(0), float64(0), float64(w), float64(h), gray)
	text.Draw(img, label, Font, 20, 25, color.White)

	return &SimpleButton{x, y, w, h, img, onClick}
}

func (b *SimpleButton) Draw(screen *ebiten.Image) {
	op := &ebiten.DrawImageOptions{}
	op.GeoM.Translate(float64(b.X), float64(b.Y))
	screen.DrawImage(b.img, op)
}

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

func (b *SimpleButton) Contains(x, y int) bool {
	return x >= b.X && x <= b.X+b.Width && y >= b.Y && y <= b.Y+b.Height
}

func (b *SimpleButton) FindObjectAt(x, y int) interface{} {
	if b.Contains(x, y) {
		return b
	}
	return nil
}