From 16a00d115252776c65c07cc7ac84cb375d28d277 Mon Sep 17 00:00:00 2001 From: Timofey Kulin Date: Tue, 23 Oct 2018 09:25:34 +0300 Subject: [PATCH] Add MeasureMultilineString method to Context. Fix #https://github.com/fogleman/gg/issues/49 --- context.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/context.go b/context.go index f436878..cbd32f7 100644 --- a/context.go +++ b/context.go @@ -8,6 +8,7 @@ import ( "image/png" "io" "math" + "strings" "github.com/golang/freetype/raster" "golang.org/x/image/draw" @@ -725,8 +726,11 @@ func (dc *Context) DrawStringAnchored(s string, x, y, ax, ay float64) { // spacing and text alignment. func (dc *Context) DrawStringWrapped(s string, x, y, ax, ay, width, lineSpacing float64, align Align) { lines := dc.WordWrap(s, width) + + // sync h formula with MeasureMultilineString h := float64(len(lines)) * dc.fontHeight * lineSpacing h -= (lineSpacing - 1) * dc.fontHeight + x -= ax * width y -= ay * h switch align { @@ -746,6 +750,29 @@ func (dc *Context) DrawStringWrapped(s string, x, y, ax, ay, width, lineSpacing } } +func (dc *Context) MeasureMultilineString(s string, lineSpacing float64) (width, height float64) { + lines := strings.Split(s, "\n") + + // sync h formula with DrawStringWrapped + height = float64(len(lines)) * dc.fontHeight * lineSpacing + height -= (lineSpacing - 1) * dc.fontHeight + + d := &font.Drawer{ + Face: dc.fontFace, + } + + // max width from lines + for _, line := range lines { + adv := d.MeasureString(line) + currentWidth := float64(adv >> 6) // from gg.Context.MeasureString + if currentWidth > width { + width = currentWidth + } + } + + return width, height +} + // MeasureString returns the rendered width and height of the specified text // given the current font face. func (dc *Context) MeasureString(s string) (w, h float64) {