MeasureText returns the minimum width and height in pixels necessary for an image to contain the specified text. The supplied text string can contain line break escape sequences (\n).
(text string)
| 170 | // MeasureText returns the minimum width and height in pixels necessary for an image to contain |
| 171 | // the specified text. The supplied text string can contain line break escape sequences (\n). |
| 172 | func (f *Font) MeasureText(text string) (int, int) { |
| 173 | |
| 174 | // Create font drawer |
| 175 | f.updateFace() |
| 176 | d := &font.Drawer{Dst: nil, Src: f.fg, Face: f.face} |
| 177 | |
| 178 | // Draw text |
| 179 | var width, height int |
| 180 | metrics := f.face.Metrics() |
| 181 | lineHeight := (metrics.Ascent + metrics.Descent).Ceil() |
| 182 | lineGap := int((f.attrib.LineSpacing - float64(1)) * float64(lineHeight)) |
| 183 | |
| 184 | lines := strings.Split(text, "\n") |
| 185 | for i, s := range lines { |
| 186 | d.Dot = fixed.P(0, height) |
| 187 | lineWidth := d.MeasureString(s).Ceil() |
| 188 | if lineWidth > width { |
| 189 | width = lineWidth |
| 190 | } |
| 191 | height += lineHeight |
| 192 | if i > 1 { |
| 193 | height += lineGap |
| 194 | } |
| 195 | } |
| 196 | return width, height |
| 197 | } |
| 198 | |
| 199 | // Metrics returns the font metrics. |
| 200 | func (f *Font) Metrics() font.Metrics { |
no test coverage detected