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
|
package ui
import (
"image/color"
"time"
"github.com/hajimehoshi/ebiten/v2"
)
var (
TIMERBAR_DEFAULT_BACKGROUND = color.Black
TIMERBAR_DEFAULT_FOREGROUND = color.White
)
type TimerBar struct {
WidgetBase
fg color.Color
bg color.Color
start time.Time
deadline time.Time
}
func NewTimerBar(x, y int, width, height int, timer time.Duration) *TimerBar {
tb := &TimerBar{
WidgetBase: NewWidgetBase(x, y, width, height),
bg: TEXTBOX_DEFAULT_BACKGROUND,
fg: TEXTBOX_DEFAULT_FOREGROUND,
start: time.Now(),
deadline: time.Now().Add(timer),
}
tb.renderImpl = func() *ebiten.Image { return tb.render() }
tb.EventHandlersMap["update"] = func() error {
if time.Now().Before(tb.deadline) {
tb.ForceRedraw()
}
return nil
}
return tb
}
func (tb *TimerBar) Bg(bg color.Color) *TimerBar {
tb.bg = bg
return tb
}
func (tb *TimerBar) Fg(fg color.Color) *TimerBar {
tb.fg = fg
return tb
}
func (tb *TimerBar) render() *ebiten.Image {
img := ebiten.NewImage(tb.Width, tb.Height)
img.Fill(tb.bg)
fraction := float64(time.Since(tb.start)) / float64(tb.deadline.Sub(tb.start))
barWidth := int(float64(tb.Width) * fraction)
if barWidth == 0 {
barWidth = 1
}
bar := ebiten.NewImage(barWidth, tb.Height)
bar.Fill(tb.fg)
op := ebiten.DrawImageOptions{}
img.DrawImage(bar, &op)
return img
}
|