zntg/ui/label.go

65 lines
1.4 KiB
Go
Raw Normal View History

package ui
import (
"opslag.de/schobers/geom"
)
type Label struct {
ControlBase
Text string
2020-05-12 18:58:42 +00:00
init bool
size *Cache
}
func BuildLabel(text string, fn func(*Label)) *Label {
var l = &Label{Text: text}
if fn != nil {
fn(l)
}
return l
}
2020-05-12 18:58:42 +00:00
func (l *Label) initialize() {
if l.init {
return
}
l.size = NewCacheContext(l.desiredSize, l.hashContent)
l.init = true
}
func (l *Label) hashContent(ctx Context) string {
return l.FontName(ctx) + l.Text
}
func (l *Label) desiredSize(ctx Context) interface{} {
fontName := l.FontName(ctx)
font := ctx.Renderer().Font(fontName)
width := font.WidthOf(l.Text)
height := font.Height()
pad := ctx.Style().Dimensions.TextPadding
return geom.PtF32(width+pad*2, height+pad*2)
}
func (l *Label) DesiredSize(ctx Context) geom.PointF32 {
2020-05-12 18:58:42 +00:00
l.initialize()
return l.size.Get(ctx).(geom.PointF32)
}
func (l *Label) Render(ctx Context) {
l.RenderBackground(ctx)
2020-05-12 18:58:42 +00:00
c := l.FontColor(ctx)
f := l.FontName(ctx)
pad := ctx.Style().Dimensions.TextPadding
bounds := l.bounds.Inset(pad)
switch l.TextAlignment {
case AlignLeft:
ctx.Renderer().TextAlign(bounds.Min, f, c, l.Text, l.TextAlignment)
case AlignRight:
ctx.Renderer().TextAlign(geom.PtF32(bounds.Max.X, bounds.Min.Y), f, c, l.Text, l.TextAlignment)
case AlignCenter:
ctx.Renderer().TextAlign(geom.PtF32(.5*(bounds.Min.X+bounds.Max.X), bounds.Min.Y), f, c, l.Text, l.TextAlignment)
}
}