summaryrefslogtreecommitdiff
path: root/engine/UI/Label.go
blob: 53c6e9621f19ce53f94df2bc90ae42d20bb2fdda (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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package ui

import (
	"encoding/json"
	"fmt"

	rl "github.com/gen2brain/raylib-go/raylib"
)

const LabelTypeName string = "label"

var defaultLabelPadding float32 = 0.1
var defaultLabelRoundness float32 = 0.2

// If the text formation formula is applied without it the text is
// overlowing on the right due to rounding errors
const overflowMultiplyer float32 = 1.1

var defaultLabelStyle = &Style{
	BacgroundColor: &rl.LightGray,
	FontColor:      &rl.DarkGray,
	Padding:        &defaultLabelPadding,
	Roundness: 		&defaultLabelRoundness,
}

type TextAlignment uint8

const (
	Center TextAlignment = iota
	Start
)

// A UI element containing a text field
type Label struct {
	WidthWeight float32
	Text string
	Alignment TextAlignment

	Style Style `json:"-"`
}

func (base *Label) Init(*Menu) {
	base.Style.FillMissing(defaultLabelStyle)
	if base.WidthWeight == 0 {
		base.WidthWeight = 1
	}
}

func (base *Label) Destroy() {
}

func (base *Label) Draw(position *rl.Rectangle) {
	// rl.TraceLog(rl.LogInfo, "Drawn at %v/%v/%v/%v", position.X, position.Y, position.Width, position.Height)
	rl.DrawRectangleRounded(*position,
		*base.Style.Roundness, 
		0, // Assume the segments param is always 0 - it doesn't really matter without a border
		*base.Style.BacgroundColor)
	var textHeight = base.getTextHeight(position)
	var textY = int32(position.Y + *base.Style.Padding)
	if base.Alignment == Center {
		textY += (int32(position.Height) - textHeight) / 2
	}
	rl.DrawText(base.Text,
		int32(position.X + *base.Style.Padding),
		textY,
		textHeight,
		*base.Style.FontColor)
}

func (base *Label) GetOccupationWeight() float32 {
	return base.WidthWeight
}

// Returns the size of the text that will not overflow in the side
func (base *Label) getTextHeight(position *rl.Rectangle) int32 {
	var width = position.Width - 2 * *base.Style.Padding
	var outp = position.Height - 2 * *base.Style.Padding
	var maxWidthSize = rl.MeasureText(base.Text, int32(outp))
	if maxWidthSize > int32(width) {
		outp /= (float32(maxWidthSize) / width) * overflowMultiplyer
	}
	return int32(outp)
}

func (base Label) String() string {
	var outp, jsonErr = json.Marshal(base)
	if jsonErr != nil {
		return fmt.Sprintf("Failed to parse settings: %s", jsonErr.Error())
	}
	return string(outp)
}