font.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. // Copyright 2015 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package font defines an interface for font faces, for drawing text on an
  5. // image.
  6. //
  7. // Other packages provide font face implementations. For example, a truetype
  8. // package would provide one based on .ttf font files.
  9. package font // import "golang.org/x/image/font"
  10. import (
  11. "image"
  12. "image/draw"
  13. "io"
  14. "unicode/utf8"
  15. "golang.org/x/image/math/fixed"
  16. )
  17. // TODO: who is responsible for caches (glyph images, glyph indices, kerns)?
  18. // The Drawer or the Face?
  19. // Face is a font face. Its glyphs are often derived from a font file, such as
  20. // "Comic_Sans_MS.ttf", but a face has a specific size, style, weight and
  21. // hinting. For example, the 12pt and 18pt versions of Comic Sans are two
  22. // different faces, even if derived from the same font file.
  23. //
  24. // A Face is not safe for concurrent use by multiple goroutines, as its methods
  25. // may re-use implementation-specific caches and mask image buffers.
  26. //
  27. // To create a Face, look to other packages that implement specific font file
  28. // formats.
  29. type Face interface {
  30. io.Closer
  31. // Glyph returns the draw.DrawMask parameters (dr, mask, maskp) to draw r's
  32. // glyph at the sub-pixel destination location dot, and that glyph's
  33. // advance width.
  34. //
  35. // It returns !ok if the face does not contain a glyph for r. This includes
  36. // returning !ok for a fallback glyph (such as substituting a U+FFFD glyph
  37. // or OpenType's .notdef glyph), in which case the other return values may
  38. // still be non-zero.
  39. //
  40. // The contents of the mask image returned by one Glyph call may change
  41. // after the next Glyph call. Callers that want to cache the mask must make
  42. // a copy.
  43. Glyph(dot fixed.Point26_6, r rune) (
  44. dr image.Rectangle, mask image.Image, maskp image.Point, advance fixed.Int26_6, ok bool)
  45. // GlyphBounds returns the bounding box of r's glyph, drawn at a dot equal
  46. // to the origin, and that glyph's advance width.
  47. //
  48. // It returns !ok if the face does not contain a glyph for r. This includes
  49. // returning !ok for a fallback glyph (such as substituting a U+FFFD glyph
  50. // or OpenType's .notdef glyph), in which case the other return values may
  51. // still be non-zero.
  52. //
  53. // The glyph's ascent and descent are equal to -bounds.Min.Y and
  54. // +bounds.Max.Y. The glyph's left-side and right-side bearings are equal
  55. // to bounds.Min.X and advance-bounds.Max.X. A visual depiction of what
  56. // these metrics are is at
  57. // https://developer.apple.com/library/archive/documentation/TextFonts/Conceptual/CocoaTextArchitecture/Art/glyphterms_2x.png
  58. GlyphBounds(r rune) (bounds fixed.Rectangle26_6, advance fixed.Int26_6, ok bool)
  59. // GlyphAdvance returns the advance width of r's glyph.
  60. //
  61. // It returns !ok if the face does not contain a glyph for r. This includes
  62. // returning !ok for a fallback glyph (such as substituting a U+FFFD glyph
  63. // or OpenType's .notdef glyph), in which case the other return values may
  64. // still be non-zero.
  65. GlyphAdvance(r rune) (advance fixed.Int26_6, ok bool)
  66. // Kern returns the horizontal adjustment for the kerning pair (r0, r1). A
  67. // positive kern means to move the glyphs further apart.
  68. Kern(r0, r1 rune) fixed.Int26_6
  69. // Metrics returns the metrics for this Face.
  70. Metrics() Metrics
  71. // TODO: ColoredGlyph for various emoji?
  72. // TODO: Ligatures? Shaping?
  73. }
  74. // Metrics holds the metrics for a Face. A visual depiction is at
  75. // https://developer.apple.com/library/mac/documentation/TextFonts/Conceptual/CocoaTextArchitecture/Art/glyph_metrics_2x.png
  76. type Metrics struct {
  77. // Height is the recommended amount of vertical space between two lines of
  78. // text.
  79. Height fixed.Int26_6
  80. // Ascent is the distance from the top of a line to its baseline.
  81. Ascent fixed.Int26_6
  82. // Descent is the distance from the bottom of a line to its baseline. The
  83. // value is typically positive, even though a descender goes below the
  84. // baseline.
  85. Descent fixed.Int26_6
  86. // XHeight is the distance from the top of non-ascending lowercase letters
  87. // to the baseline.
  88. XHeight fixed.Int26_6
  89. // CapHeight is the distance from the top of uppercase letters to the
  90. // baseline.
  91. CapHeight fixed.Int26_6
  92. // CaretSlope is the slope of a caret as a vector with the Y axis pointing up.
  93. // The slope {0, 1} is the vertical caret.
  94. CaretSlope image.Point
  95. }
  96. // Drawer draws text on a destination image.
  97. //
  98. // A Drawer is not safe for concurrent use by multiple goroutines, since its
  99. // Face is not.
  100. type Drawer struct {
  101. // Dst is the destination image.
  102. Dst draw.Image
  103. // Src is the source image.
  104. Src image.Image
  105. // Face provides the glyph mask images.
  106. Face Face
  107. // Dot is the baseline location to draw the next glyph. The majority of the
  108. // affected pixels will be above and to the right of the dot, but some may
  109. // be below or to the left. For example, drawing a 'j' in an italic face
  110. // may affect pixels below and to the left of the dot.
  111. Dot fixed.Point26_6
  112. // TODO: Clip image.Image?
  113. // TODO: SrcP image.Point for Src images other than *image.Uniform? How
  114. // does it get updated during DrawString?
  115. }
  116. // TODO: should DrawString return the last rune drawn, so the next DrawString
  117. // call can kern beforehand? Or should that be the responsibility of the caller
  118. // if they really want to do that, since they have to explicitly shift d.Dot
  119. // anyway? What if ligatures span more than two runes? What if grapheme
  120. // clusters span multiple runes?
  121. //
  122. // TODO: do we assume that the input is in any particular Unicode Normalization
  123. // Form?
  124. //
  125. // TODO: have DrawRunes(s []rune)? DrawRuneReader(io.RuneReader)?? If we take
  126. // io.RuneReader, we can't assume that we can rewind the stream.
  127. //
  128. // TODO: how does this work with line breaking: drawing text up until a
  129. // vertical line? Should DrawString return the number of runes drawn?
  130. // DrawBytes draws s at the dot and advances the dot's location.
  131. //
  132. // It is equivalent to DrawString(string(s)) but may be more efficient.
  133. func (d *Drawer) DrawBytes(s []byte) {
  134. prevC := rune(-1)
  135. for len(s) > 0 {
  136. c, size := utf8.DecodeRune(s)
  137. s = s[size:]
  138. if prevC >= 0 {
  139. d.Dot.X += d.Face.Kern(prevC, c)
  140. }
  141. dr, mask, maskp, advance, _ := d.Face.Glyph(d.Dot, c)
  142. if !dr.Empty() {
  143. draw.DrawMask(d.Dst, dr, d.Src, image.Point{}, mask, maskp, draw.Over)
  144. }
  145. d.Dot.X += advance
  146. prevC = c
  147. }
  148. }
  149. // DrawString draws s at the dot and advances the dot's location.
  150. func (d *Drawer) DrawString(s string) {
  151. prevC := rune(-1)
  152. for _, c := range s {
  153. if prevC >= 0 {
  154. d.Dot.X += d.Face.Kern(prevC, c)
  155. }
  156. dr, mask, maskp, advance, _ := d.Face.Glyph(d.Dot, c)
  157. if !dr.Empty() {
  158. draw.DrawMask(d.Dst, dr, d.Src, image.Point{}, mask, maskp, draw.Over)
  159. }
  160. d.Dot.X += advance
  161. prevC = c
  162. }
  163. }
  164. // BoundBytes returns the bounding box of s, drawn at the drawer dot, as well as
  165. // the advance.
  166. //
  167. // It is equivalent to BoundBytes(string(s)) but may be more efficient.
  168. func (d *Drawer) BoundBytes(s []byte) (bounds fixed.Rectangle26_6, advance fixed.Int26_6) {
  169. bounds, advance = BoundBytes(d.Face, s)
  170. bounds.Min = bounds.Min.Add(d.Dot)
  171. bounds.Max = bounds.Max.Add(d.Dot)
  172. return
  173. }
  174. // BoundString returns the bounding box of s, drawn at the drawer dot, as well
  175. // as the advance.
  176. func (d *Drawer) BoundString(s string) (bounds fixed.Rectangle26_6, advance fixed.Int26_6) {
  177. bounds, advance = BoundString(d.Face, s)
  178. bounds.Min = bounds.Min.Add(d.Dot)
  179. bounds.Max = bounds.Max.Add(d.Dot)
  180. return
  181. }
  182. // MeasureBytes returns how far dot would advance by drawing s.
  183. //
  184. // It is equivalent to MeasureString(string(s)) but may be more efficient.
  185. func (d *Drawer) MeasureBytes(s []byte) (advance fixed.Int26_6) {
  186. return MeasureBytes(d.Face, s)
  187. }
  188. // MeasureString returns how far dot would advance by drawing s.
  189. func (d *Drawer) MeasureString(s string) (advance fixed.Int26_6) {
  190. return MeasureString(d.Face, s)
  191. }
  192. // BoundBytes returns the bounding box of s with f, drawn at a dot equal to the
  193. // origin, as well as the advance.
  194. //
  195. // It is equivalent to BoundString(string(s)) but may be more efficient.
  196. func BoundBytes(f Face, s []byte) (bounds fixed.Rectangle26_6, advance fixed.Int26_6) {
  197. prevC := rune(-1)
  198. for len(s) > 0 {
  199. c, size := utf8.DecodeRune(s)
  200. s = s[size:]
  201. if prevC >= 0 {
  202. advance += f.Kern(prevC, c)
  203. }
  204. b, a, _ := f.GlyphBounds(c)
  205. if !b.Empty() {
  206. b.Min.X += advance
  207. b.Max.X += advance
  208. bounds = bounds.Union(b)
  209. }
  210. advance += a
  211. prevC = c
  212. }
  213. return
  214. }
  215. // BoundString returns the bounding box of s with f, drawn at a dot equal to the
  216. // origin, as well as the advance.
  217. func BoundString(f Face, s string) (bounds fixed.Rectangle26_6, advance fixed.Int26_6) {
  218. prevC := rune(-1)
  219. for _, c := range s {
  220. if prevC >= 0 {
  221. advance += f.Kern(prevC, c)
  222. }
  223. b, a, _ := f.GlyphBounds(c)
  224. if !b.Empty() {
  225. b.Min.X += advance
  226. b.Max.X += advance
  227. bounds = bounds.Union(b)
  228. }
  229. advance += a
  230. prevC = c
  231. }
  232. return
  233. }
  234. // MeasureBytes returns how far dot would advance by drawing s with f.
  235. //
  236. // It is equivalent to MeasureString(string(s)) but may be more efficient.
  237. func MeasureBytes(f Face, s []byte) (advance fixed.Int26_6) {
  238. prevC := rune(-1)
  239. for len(s) > 0 {
  240. c, size := utf8.DecodeRune(s)
  241. s = s[size:]
  242. if prevC >= 0 {
  243. advance += f.Kern(prevC, c)
  244. }
  245. a, _ := f.GlyphAdvance(c)
  246. advance += a
  247. prevC = c
  248. }
  249. return advance
  250. }
  251. // MeasureString returns how far dot would advance by drawing s with f.
  252. func MeasureString(f Face, s string) (advance fixed.Int26_6) {
  253. prevC := rune(-1)
  254. for _, c := range s {
  255. if prevC >= 0 {
  256. advance += f.Kern(prevC, c)
  257. }
  258. a, _ := f.GlyphAdvance(c)
  259. advance += a
  260. prevC = c
  261. }
  262. return advance
  263. }
  264. // Hinting selects how to quantize a vector font's glyph nodes.
  265. //
  266. // Not all fonts support hinting.
  267. type Hinting int
  268. const (
  269. HintingNone Hinting = iota
  270. HintingVertical
  271. HintingFull
  272. )
  273. // Stretch selects a normal, condensed, or expanded face.
  274. //
  275. // Not all fonts support stretches.
  276. type Stretch int
  277. const (
  278. StretchUltraCondensed Stretch = -4
  279. StretchExtraCondensed Stretch = -3
  280. StretchCondensed Stretch = -2
  281. StretchSemiCondensed Stretch = -1
  282. StretchNormal Stretch = +0
  283. StretchSemiExpanded Stretch = +1
  284. StretchExpanded Stretch = +2
  285. StretchExtraExpanded Stretch = +3
  286. StretchUltraExpanded Stretch = +4
  287. )
  288. // Style selects a normal, italic, or oblique face.
  289. //
  290. // Not all fonts support styles.
  291. type Style int
  292. const (
  293. StyleNormal Style = iota
  294. StyleItalic
  295. StyleOblique
  296. )
  297. // Weight selects a normal, light or bold face.
  298. //
  299. // Not all fonts support weights.
  300. //
  301. // The named Weight constants (e.g. WeightBold) correspond to CSS' common
  302. // weight names (e.g. "Bold"), but the numerical values differ, so that in Go,
  303. // the zero value means to use a normal weight. For the CSS names and values,
  304. // see https://developer.mozilla.org/en/docs/Web/CSS/font-weight
  305. type Weight int
  306. const (
  307. WeightThin Weight = -3 // CSS font-weight value 100.
  308. WeightExtraLight Weight = -2 // CSS font-weight value 200.
  309. WeightLight Weight = -1 // CSS font-weight value 300.
  310. WeightNormal Weight = +0 // CSS font-weight value 400.
  311. WeightMedium Weight = +1 // CSS font-weight value 500.
  312. WeightSemiBold Weight = +2 // CSS font-weight value 600.
  313. WeightBold Weight = +3 // CSS font-weight value 700.
  314. WeightExtraBold Weight = +4 // CSS font-weight value 800.
  315. WeightBlack Weight = +5 // CSS font-weight value 900.
  316. )