Allow specifying widget background color

This commit is contained in:
Trevor Slocum 2023-10-25 20:51:19 -07:00
parent 7515991afc
commit af162c64b6
4 changed files with 46 additions and 12 deletions

22
box.go
View file

@ -2,15 +2,17 @@ package etk
import (
"image"
"image/color"
"sync"
"github.com/hajimehoshi/ebiten/v2"
)
type Box struct {
rect image.Rectangle
children []Widget
visible bool
rect image.Rectangle
children []Widget
background color.RGBA
visible bool
sync.Mutex
}
@ -35,6 +37,20 @@ func (b *Box) SetRect(r image.Rectangle) {
b.rect = r
}
func (b *Box) Background() color.RGBA {
b.Lock()
defer b.Unlock()
return b.background
}
func (b *Box) SetBackground(background color.RGBA) {
b.Lock()
defer b.Unlock()
b.background = background
}
func (b *Box) SetFocus(focus bool) bool {
return false
}

13
game.go
View file

@ -135,10 +135,6 @@ func update(w Widget, cursor image.Point, pressed bool, clicked bool, mouseHandl
var err error
children := w.Children()
for _, child := range children {
if !child.Visible() {
continue
}
mouseHandled, keyboardHandled, err = update(child, cursor, pressed, clicked, mouseHandled, keyboardHandled)
if err != nil {
return false, false, err
@ -177,6 +173,11 @@ func draw(w Widget, screen *ebiten.Image) error {
return nil
}
background := w.Background()
if background.A > 0 {
screen.SubImage(w.Rect()).(*ebiten.Image).Fill(background)
}
err := w.Draw(screen)
if err != nil {
return fmt.Errorf("failed to draw widget: %s", err)
@ -184,10 +185,6 @@ func draw(w Widget, screen *ebiten.Image) error {
children := w.Children()
for _, child := range children {
if !child.Visible() {
continue
}
err = draw(child, screen)
if err != nil {
return fmt.Errorf("failed to draw widget: %s", err)

20
text.go
View file

@ -2,6 +2,7 @@ package etk
import (
"image"
"image/color"
"code.rocketnine.space/tslocum/messeji"
"github.com/hajimehoshi/ebiten/v2"
@ -10,7 +11,8 @@ import (
type Text struct {
*messeji.TextField
children []Widget
background color.RGBA
children []Widget
}
func NewText(text string) *Text {
@ -26,6 +28,20 @@ func NewText(text string) *Text {
}
}
func (t *Text) Background() color.RGBA {
t.Lock()
defer t.Unlock()
return t.background
}
func (t *Text) SetBackground(background color.RGBA) {
t.Lock()
defer t.Unlock()
t.background = background
}
func (t *Text) SetFocus(focus bool) bool {
return false
}
@ -79,3 +95,5 @@ func (t *Text) Draw(screen *ebiten.Image) error {
t.TextField.Draw(screen)
return nil
}
var _ Widget = &Text{}

View file

@ -2,6 +2,7 @@ package etk
import (
"image"
"image/color"
"github.com/hajimehoshi/ebiten/v2"
)
@ -9,6 +10,8 @@ import (
type Widget interface {
Rect() image.Rectangle
SetRect(r image.Rectangle)
Background() color.RGBA
SetBackground(background color.RGBA)
SetFocus(focus bool) (accept bool)
SetVisible(visible bool)
Visible() bool