2015-05-25 12:11:55 +00:00
|
|
|
// Some of this code (namely the code for computing the
|
|
|
|
// width of a string in a given font) was copied from
|
|
|
|
// code.google.com/p/freetype-go/freetype/ which includes
|
|
|
|
// the following copyright notice:
|
|
|
|
// Copyright 2010 The Freetype-Go Authors. All rights reserved.
|
|
|
|
package main
|
|
|
|
|
2016-06-28 17:35:48 +00:00
|
|
|
import (
|
|
|
|
"github.com/golang/freetype/truetype"
|
|
|
|
"golang.org/x/image/math/fixed"
|
|
|
|
)
|
2015-05-25 12:11:55 +00:00
|
|
|
|
|
|
|
const (
|
|
|
|
fontSize = 11
|
|
|
|
)
|
|
|
|
|
|
|
|
func calculateTextWidth(text string) (int, error) {
|
|
|
|
binFont, _ := Asset("assets/DejaVuSans.ttf")
|
|
|
|
font, err := truetype.Parse(binFont)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
scale := fontSize / float64(font.FUnitsPerEm())
|
|
|
|
|
|
|
|
width := 0
|
|
|
|
prev, hasPrev := truetype.Index(0), false
|
|
|
|
for _, rune := range text {
|
2016-06-28 17:35:48 +00:00
|
|
|
fUnitsPerEm := fixed.Int26_6(font.FUnitsPerEm())
|
2015-05-25 12:11:55 +00:00
|
|
|
index := font.Index(rune)
|
|
|
|
if hasPrev {
|
2016-06-28 17:35:48 +00:00
|
|
|
width += int(font.Kern(fUnitsPerEm, prev, index))
|
2015-05-25 12:11:55 +00:00
|
|
|
}
|
2016-06-28 17:35:48 +00:00
|
|
|
width += int(font.HMetric(fUnitsPerEm, index).AdvanceWidth)
|
2015-05-25 12:11:55 +00:00
|
|
|
prev, hasPrev = index, true
|
|
|
|
}
|
|
|
|
|
|
|
|
return int(float64(width) * scale), nil
|
|
|
|
}
|