Width returns width of a string when drawn using the font.
(s string)
| 140 | |
| 141 | // Width returns width of a string when drawn using the font. |
| 142 | func (f *Face) Width(s string) Length { |
| 143 | var ( |
| 144 | pixelsPerEm = fixed.Int26_6(f.Face.UnitsPerEm()) |
| 145 | |
| 146 | // scale converts sfnt.Unit to float64 |
| 147 | scale = f.Font.Size / Points(float64(pixelsPerEm)) |
| 148 | |
| 149 | width = 0 |
| 150 | hasPrev = false |
| 151 | buf sfnt.Buffer |
| 152 | prev, idx sfnt.GlyphIndex |
| 153 | hinting = defaultHinting |
| 154 | ) |
| 155 | for _, rune := range s { |
| 156 | var err error |
| 157 | idx, err = f.Face.GlyphIndex(&buf, rune) |
| 158 | if err != nil { |
| 159 | panic(fmt.Errorf("could not get glyph index: %v", err)) |
| 160 | } |
| 161 | if hasPrev { |
| 162 | kern, err := f.Face.Kern(&buf, prev, idx, pixelsPerEm, hinting) |
| 163 | switch { |
| 164 | case err == nil: |
| 165 | width += int(kern) |
| 166 | case errors.Is(err, sfnt.ErrNotFound): |
| 167 | // no-op |
| 168 | default: |
| 169 | panic(fmt.Errorf("could not get kerning: %v", err)) |
| 170 | } |
| 171 | } |
| 172 | adv, err := f.Face.GlyphAdvance(&buf, idx, pixelsPerEm, hinting) |
| 173 | if err != nil { |
| 174 | panic(fmt.Errorf("could not retrieve glyph's advance: %v", err)) |
| 175 | } |
| 176 | width += int(adv) |
| 177 | prev, hasPrev = idx, true |
| 178 | } |
| 179 | return Points(float64(width)) * scale |
| 180 | } |
| 181 | |
| 182 | // Collection is a collection of fonts, regrouped under a common typeface. |
| 183 | type Collection []Face |