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.15 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 { Weight float32 Text string Alignment TextAlignment Style Style `json:"-"` BackgroundElement UIElement } func (base *Label) Init(menu *Menu) { base.Style.FillMissing(defaultLabelStyle) if base.Weight == 0 { base.Weight = 1 } if base.BackgroundElement != nil { base.BackgroundElement.Init(menu) } } func (base *Label) Destroy() { } func (base *Label) GetOccupationWeight() float32 { return base.Weight } 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) drawStackedElementBackground(base, position) var textHeight = base.getTextHeight(position) var textY = int32(position.Y) if base.Alignment == Center { textY += (int32(position.Height) - textHeight) / 2 } rl.DrawText(base.Text, int32(position.X + (*base.Style.Padding * position.Width)), textY, textHeight, *base.Style.FontColor) } func (base *Label) GetStyle() *Style { return &base.Style } func (base *Label) GetBackgroundElement() UIElement { return base.BackgroundElement } // 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 label: %s", jsonErr.Error()) } return string(outp) }