...

Source file src/code.rocketnine.space/tslocum/etk/button.go

Documentation: code.rocketnine.space/tslocum/etk

     1  package etk
     2  
     3  import (
     4  	"image"
     5  
     6  	"code.rocketnine.space/tslocum/messeji"
     7  	"github.com/hajimehoshi/ebiten/v2"
     8  )
     9  
    10  type Button struct {
    11  	*Box
    12  
    13  	label *messeji.TextField
    14  
    15  	onSelected func() error
    16  }
    17  
    18  func NewButton(label string, onSelected func() error) *Button {
    19  	textColor := Style.ButtonTextColor
    20  	if textColor == nil {
    21  		textColor = Style.TextColorDark
    22  	}
    23  
    24  	l := messeji.NewTextField(Style.TextFont)
    25  	l.SetText(label)
    26  	l.SetForegroundColor(textColor)
    27  	l.SetBackgroundColor(transparent)
    28  	l.SetHorizontal(messeji.AlignCenter)
    29  	l.SetVertical(messeji.AlignCenter)
    30  
    31  	return &Button{
    32  		Box:        NewBox(),
    33  		label:      l,
    34  		onSelected: onSelected,
    35  	}
    36  }
    37  
    38  func (b *Button) SetRect(r image.Rectangle) {
    39  	b.Box.rect = r
    40  
    41  	b.label.SetRect(r)
    42  }
    43  
    44  func (b *Button) HandleMouse(cursor image.Point, pressed bool, clicked bool) (handled bool, err error) {
    45  	if !clicked {
    46  		return true, nil
    47  	}
    48  
    49  	b.Lock()
    50  	onSelected := b.onSelected
    51  	if onSelected == nil {
    52  		b.Unlock()
    53  		return true, nil
    54  	}
    55  	b.Unlock()
    56  
    57  	return true, onSelected()
    58  }
    59  
    60  func (b *Button) HandleKeyboard() (handled bool, err error) {
    61  	return false, nil
    62  }
    63  
    64  func (b *Button) Draw(screen *ebiten.Image) error {
    65  	// TODO background color
    66  	// Draw background.
    67  	screen.SubImage(b.rect).(*ebiten.Image).Fill(Style.ButtonBgColor)
    68  
    69  	// Draw label.
    70  	b.label.Draw(screen)
    71  
    72  	// Draw border.
    73  	const borderSize = 4
    74  	screen.SubImage(image.Rect(b.rect.Min.X, b.rect.Min.Y, b.rect.Max.X, b.rect.Min.Y+borderSize)).(*ebiten.Image).Fill(Style.BorderColor)
    75  	screen.SubImage(image.Rect(b.rect.Min.X, b.rect.Max.Y-borderSize, b.rect.Max.X, b.rect.Max.Y)).(*ebiten.Image).Fill(Style.BorderColor)
    76  	screen.SubImage(image.Rect(b.rect.Min.X, b.rect.Min.Y, b.rect.Min.X+borderSize, b.rect.Max.Y)).(*ebiten.Image).Fill(Style.BorderColor)
    77  	screen.SubImage(image.Rect(b.rect.Max.X-borderSize, b.rect.Min.Y, b.rect.Max.X, b.rect.Max.Y)).(*ebiten.Image).Fill(Style.BorderColor)
    78  
    79  	return nil
    80  }
    81  

View as plain text