zntg/ui/label.go

66 lines
1.5 KiB
Go
Raw Normal View History

package ui
import (
2020-12-12 13:46:52 +00:00
"image/color"
"opslag.de/schobers/geom"
)
type Label struct {
ControlBase
2020-12-12 13:46:52 +00:00
Text string
DropShadow color.Color
desired CachedValue
}
func BuildLabel(text string, fn func(*Label)) *Label {
var l = &Label{Text: text}
if fn != nil {
fn(l)
}
return l
}
func (l *Label) hashDesiredSize(ctx Context) string {
2020-05-12 18:58:42 +00:00
return l.FontName(ctx) + l.Text
}
func (l *Label) desiredSize(ctx Context) interface{} {
fontName := l.FontName(ctx)
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)
}
func (l *Label) DesiredSize(ctx Context, _ geom.PointF32) geom.PointF32 {
return l.desired.GetContext(ctx, l.desiredSize, l.hashDesiredSize).(geom.PointF32)
}
2020-12-12 13:46:52 +00:00
func (l *Label) getLabelTopLeft(ctx Context) geom.PointF32 {
2020-05-12 18:58:42 +00:00
pad := ctx.Style().Dimensions.TextPadding
bounds := l.bounds.Inset(pad)
switch l.TextAlignment {
case AlignRight:
2020-12-12 13:46:52 +00:00
return geom.PtF32(bounds.Max.X, bounds.Min.Y)
case AlignCenter:
2020-12-12 13:46:52 +00:00
return geom.PtF32(.5*(bounds.Min.X+bounds.Max.X), bounds.Min.Y)
default:
return bounds.Min
}
}
func (l *Label) Render(ctx Context) {
l.RenderBackground(ctx)
fontColor := l.TextColor(ctx)
fontName := l.FontName(ctx)
topLeft := l.getLabelTopLeft(ctx)
if l.DropShadow != nil {
ctx.Fonts().TextAlign(fontName, topLeft.Add2D(1, 1), l.DropShadow, l.Text, l.TextAlignment)
}
2020-12-12 13:46:52 +00:00
ctx.Fonts().TextAlign(fontName, topLeft, fontColor, l.Text, l.TextAlignment)
}