From 36d620108c2844bf59f3f5a5c35fe34c6edfde4a Mon Sep 17 00:00:00 2001 From: Sander Schobers Date: Thu, 4 Jul 2019 22:15:32 +0200 Subject: [PATCH] Optimized rendering a lot of labels. - Added caching of the desired size of a label. --- ui/desiredsizecache.go | 21 +++++++++++++++++++++ ui/label.go | 14 +++++++++----- 2 files changed, 30 insertions(+), 5 deletions(-) create mode 100644 ui/desiredsizecache.go diff --git a/ui/desiredsizecache.go b/ui/desiredsizecache.go new file mode 100644 index 0000000..314fdc7 --- /dev/null +++ b/ui/desiredsizecache.go @@ -0,0 +1,21 @@ +package ui + +import ( + "github.com/minio/highwayhash" + "opslag.de/schobers/geom" +) + +type desiredSizeCache struct { + sum [32]byte + size geom.PointF32 +} + +func (c *desiredSizeCache) Update(ctx Context, data string, calcFn func(Context) geom.PointF32) geom.PointF32 { + var key = [32]byte{} + sum := highwayhash.Sum([]byte(data), key[:]) + if c.sum != sum { + c.size = calcFn(ctx) + c.sum = sum + } + return c.size +} diff --git a/ui/label.go b/ui/label.go index 8328fe5..96c588d 100644 --- a/ui/label.go +++ b/ui/label.go @@ -8,6 +8,8 @@ type Label struct { ControlBase Text string + + size desiredSizeCache } func BuildLabel(text string, fn func(*Label)) *Label { @@ -20,11 +22,13 @@ func BuildLabel(text string, fn func(*Label)) *Label { func (l *Label) DesiredSize(ctx Context) geom.PointF32 { var fontName = l.FontName(ctx) - var font = ctx.Renderer().Font(fontName) - var width = font.WidthOf(l.Text) - var height = font.Height() - var pad = ctx.Style().Dimensions.TextPadding - return geom.PtF32(width+pad*2, height+pad*2) + return l.size.Update(ctx, fontName+l.Text, func(ctx Context) geom.PointF32 { + var font = ctx.Renderer().Font(fontName) + var width = font.WidthOf(l.Text) + var height = font.Height() + var pad = ctx.Style().Dimensions.TextPadding + return geom.PtF32(width+pad*2, height+pad*2) + }) } func (l *Label) Render(ctx Context) {