text/shaper: lookup closest font by weight

Signed-off-by: Walter Werner SCHNEIDER <contact@schnwalter.eu>
This commit is contained in:
Walter Werner SCHNEIDER
2021-09-02 22:20:38 +03:00
committed by Elias Naur
parent 23f6dcb868
commit 49a7b2e6f4
3 changed files with 163 additions and 15 deletions
+33 -15
View File
@@ -56,24 +56,42 @@ func (c *Cache) lookup(font Font) *faceCache {
}
func (c *Cache) faceForStyle(font Font) *faceCache {
tf := c.faces[font]
if tf == nil {
font := font
font.Weight = Normal
tf = c.faces[font]
if closest, ok := c.closestFont(font); ok {
return c.faces[closest]
}
if tf == nil {
font := font
font.Style = Regular
tf = c.faces[font]
font.Style = Regular
if closest, ok := c.closestFont(font); ok {
return c.faces[closest]
}
if tf == nil {
font := font
font.Style = Regular
font.Weight = Normal
tf = c.faces[font]
return nil
}
// closestFont returns the closest Font by weight, in case of equality the
// lighter weight will be returned.
func (c *Cache) closestFont(lookup Font) (Font, bool) {
if c.faces[lookup] != nil {
return lookup, true
}
return tf
found := false
var match Font
for cf := range c.faces {
if cf.Typeface != lookup.Typeface || cf.Variant != lookup.Variant || cf.Style != lookup.Style {
continue
}
if !found {
found = true
match = cf
continue
}
cDist := weightDistance(lookup.Weight, cf.Weight)
mDist := weightDistance(lookup.Weight, match.Weight)
if cDist < mDist {
match = cf
} else if cDist == mDist && cf.Weight < match.Weight {
match = cf
}
}
return match, found
}
func NewCache(collection []FontFace) *Cache {