2019-03-05 20:52:18 +00:00
|
|
|
package ui
|
|
|
|
|
|
|
|
import (
|
|
|
|
"opslag.de/schobers/geom"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Label struct {
|
|
|
|
ControlBase
|
|
|
|
|
|
|
|
Text string
|
2019-07-04 20:15:32 +00:00
|
|
|
|
2020-05-12 18:58:42 +00:00
|
|
|
init bool
|
|
|
|
size *Cache
|
2019-03-05 20:52:18 +00:00
|
|
|
}
|
|
|
|
|
2019-03-12 20:11:43 +00:00
|
|
|
func BuildLabel(text string, fn func(*Label)) *Label {
|
2019-03-05 20:52:18 +00:00
|
|
|
var l = &Label{Text: text}
|
2019-03-12 20:11:43 +00:00
|
|
|
if fn != nil {
|
|
|
|
fn(l)
|
|
|
|
}
|
2019-03-05 20:52:18 +00:00
|
|
|
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)
|
2020-05-15 13:42:24 +00:00
|
|
|
font := ctx.Fonts().Font(fontName)
|
2020-05-12 18:58:42 +00:00
|
|
|
width := font.WidthOf(l.Text)
|
|
|
|
height := font.Height()
|
|
|
|
pad := ctx.Style().Dimensions.TextPadding
|
|
|
|
return geom.PtF32(width+pad*2, height+pad*2)
|
|
|
|
}
|
|
|
|
|
2019-03-05 20:52:18 +00:00
|
|
|
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)
|
2019-03-05 20:52:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (l *Label) Render(ctx Context) {
|
|
|
|
l.RenderBackground(ctx)
|
2020-05-15 13:42:24 +00:00
|
|
|
fontColor := l.FontColor(ctx)
|
|
|
|
fontName := l.FontName(ctx)
|
2020-05-12 18:58:42 +00:00
|
|
|
pad := ctx.Style().Dimensions.TextPadding
|
|
|
|
bounds := l.bounds.Inset(pad)
|
2019-07-09 17:07:40 +00:00
|
|
|
switch l.TextAlignment {
|
|
|
|
case AlignLeft:
|
2020-05-15 13:42:24 +00:00
|
|
|
ctx.Fonts().TextAlign(fontName, bounds.Min, fontColor, l.Text, l.TextAlignment)
|
2019-07-09 17:07:40 +00:00
|
|
|
case AlignRight:
|
2020-05-15 13:42:24 +00:00
|
|
|
ctx.Fonts().TextAlign(fontName, geom.PtF32(bounds.Max.X, bounds.Min.Y), fontColor, l.Text, l.TextAlignment)
|
2019-07-09 17:07:40 +00:00
|
|
|
case AlignCenter:
|
2020-05-15 13:42:24 +00:00
|
|
|
ctx.Fonts().TextAlign(fontName, geom.PtF32(.5*(bounds.Min.X+bounds.Max.X), bounds.Min.Y), fontColor, l.Text, l.TextAlignment)
|
2019-07-09 17:07:40 +00:00
|
|
|
}
|
2019-03-05 20:52:18 +00:00
|
|
|
}
|