| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
"""Transform a font to center each of its characters in square bounding boxes. |
| 13 |
|
| 14 |
See https://stackoverflow.com/questions/37377476/ for background information. |
| 15 |
|
| 16 |
This script is here for reference. It was used to generate the modified |
| 17 |
font RocqNotations.ttf from UbuntuMono-B.ttf. |
| 18 |
""" |
| 19 |
|
| 20 |
from collections import Counter |
| 21 |
|
| 22 |
try: |
| 23 |
import fontforge |
| 24 |
import psMat |
| 25 |
except ImportError: |
| 26 |
print("This program requires FontForge's python bindings:") |
| 27 |
print(" git clone https://github.com/fontforge/fontforge") |
| 28 |
print(" cd fontforge") |
| 29 |
print(" ./bootstrap") |
| 30 |
print(" ./configure") |
| 31 |
print(" make -j8") |
| 32 |
print(" sudo make install") |
| 33 |
raise |
| 34 |
|
| 35 |
def glyph_height(glyph): |
| 36 |
_, ylo, _, yhi = glyph.boundingBox() |
| 37 |
return yhi - ylo |
| 38 |
|
| 39 |
def scale_single_glyph(glyph, width, height): |
| 40 |
"""Center glyph in a box of size width*height""" |
| 41 |
d moving the |
| 42 |
|
| 43 |
|
| 44 |
glyph.unlinkThisGlyph() |
| 45 |
|
| 46 |
deltaw = width - glyph.width |
| 47 |
glyph.left_side_bearing += deltaw / 2 |
| 48 |
glyph.right_side_bearing += deltaw - glyph.left_side_bearing |
| 49 |
glyph.width = width |
| 50 |
|
| 51 |
ylo = glyph.boundingBox()[1] |
| 52 |
deltah = height - glyph_height(glyph) |
| 53 |
glyph.transform(psMat.translate(0, deltah / 2.0 - ylo)) |
| 54 |
|
| 55 |
def avg(lst): |
| 56 |
lst = list(lst) |
| 57 |
return sum(lst) / float(len(lst)) |
| 58 |
|
| 59 |
def trim_font(fnt): |
| 60 |
"""Remove characters codes beyond 191 front fnt""" |
| 61 |
for g in fnt.glyphs(): |
| 62 |
if g.unicode >= 191: |
| 63 |
fnt.removeGlyph(g) |
| 64 |
return fnt |
| 65 |
|
| 66 |
def center_glyphs(src_font_path, dst_font_path, dst_name): |
| 67 |
fnt = trim_font(fontforge.open(src_font_path)) |
| 68 |
|
| 69 |
size = max(g.width for g in fnt.glyphs()) |
| 70 |
fnt.ascent, fnt.descent = size, 0 |
| 71 |
for glyph in fnt.glyphs(): |
| 72 |
scale_single_glyph(glyph, size, size) |
| 73 |
|
| 74 |
fnt.sfnt_names = [] |
| 75 |
fnt.fontname = fnt.familyname = fnt.fullname = dst_name |
| 76 |
fnt.generate(dst_font_path) |
| 77 |
|
| 78 |
if __name__ == '__main__': |
| 79 |
from os.path import dirname, join, abspath |
| 80 |
curdir = dirname(abspath(__file__)) |
| 81 |
ubuntumono_path = join(curdir, "UbuntuMono-B.ttf") |
| 82 |
ubuntumono_mod_path = join(curdir, "RocqNotations.ttf") |
| 83 |
center_glyphs(ubuntumono_path, ubuntumono_mod_path, "RocqNotations") |