...
1 package etk
2
3 import (
4 "image"
5
6 "github.com/hajimehoshi/ebiten/v2"
7 )
8
9 type Flex struct {
10 *Box
11
12 vertical bool
13 }
14
15 func NewFlex() *Flex {
16 return &Flex{
17 Box: NewBox(),
18 }
19 }
20
21 func (f *Flex) SetRect(r image.Rectangle) {
22 f.Lock()
23 defer f.Unlock()
24
25 f.Box.rect = r
26 f.reposition()
27 }
28
29 func (f *Flex) SetVertical(v bool) {
30 f.Lock()
31 defer f.Unlock()
32
33 if f.vertical == v {
34 return
35 }
36
37 f.vertical = v
38 f.reposition()
39 }
40
41 func (f *Flex) HandleMouse(cursor image.Point, pressed bool, clicked bool) (handled bool, err error) {
42 return false, nil
43 }
44
45 func (f *Flex) HandleKeyboard() (handled bool, err error) {
46 return false, nil
47 }
48
49 func (f *Flex) Draw(screen *ebiten.Image) error {
50 f.Lock()
51 defer f.Unlock()
52
53 for _, child := range f.children {
54 err := child.Draw(screen)
55 if err != nil {
56 return err
57 }
58 }
59
60 return nil
61 }
62
63 func (f *Flex) reposition() {
64 l := len(f.children)
65 r := f.rect
66
67 if f.vertical {
68 childHeight := float64(r.Dy()) / float64(l)
69
70 minY := r.Min.Y
71 for i, child := range f.children {
72 maxY := r.Min.Y + int(childHeight*float64(i+1))
73 if i == l-1 {
74 maxY = r.Max.Y
75 }
76 child.SetRect(image.Rect(r.Min.X, minY, r.Max.X, maxY))
77
78 minY = maxY
79 }
80
81 return
82 }
83
84 childWidth := float64(r.Dx()) / float64(l)
85
86 minX := r.Min.X
87 for i, child := range f.children {
88 maxX := r.Min.X + int(childWidth*float64(i+1))
89 if i == l-1 {
90 maxX = r.Max.X
91 }
92 child.SetRect(image.Rect(minX, r.Min.Y, maxX, r.Max.Y))
93
94 minX = maxX
95 }
96 }
97
View as plain text