本文整理匯總了Python中fontTools.ttLib.TTFont方法的典型用法代碼示例。如果您正苦於以下問題:Python ttLib.TTFont方法的具體用法?Python ttLib.TTFont怎麽用?Python ttLib.TTFont使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類fontTools.ttLib
的用法示例。
在下文中一共展示了ttLib.TTFont方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: ExtractName
# 需要導入模塊: from fontTools import ttLib [as 別名]
# 或者: from fontTools.ttLib import TTFont [as 別名]
def ExtractName(font_or_file, name_id, default):
"""Extracts a name table field (first value if many) from a font.
Args:
font_or_file: path to a font file or a TTFont.
name_id: the ID of the name desired. Use NAME_* constant.
default: result if no value is present.
Returns:
The value of the first entry for name_id or default if there isn't one.
"""
value = default
names = []
if isinstance(font_or_file, ttLib.TTFont):
names = ExtractNames(font_or_file, name_id)
else:
with contextlib.closing(ttLib.TTFont(font_or_file)) as font:
names = ExtractNames(font, name_id)
if names:
value = names[0]
return value
示例2: VFWeight
# 需要導入模塊: from fontTools import ttLib [as 別名]
# 或者: from fontTools.ttLib import TTFont [as 別名]
def VFWeight(font):
"""Return a variable fonts weight. Return 400 if 400 is within the wght
axis range else return the value closest to 400
Args:
font: TTFont
Returns:
weight: integer
"""
wght_axis = None
for axis in font['fvar'].axes:
if axis.axisTag == "wght":
wght_axis = axis
break
value = 400
if wght_axis:
if wght_axis.minValue >= 400:
value = wght_axis.minValue
if wght_axis.maxValue <= 400:
value = wght_axis.maxValue
# TODO (MF) check with GF Eng if we should just assume it's safe to return
# 400 if a wght axis doesn't exist.
return int(value)
示例3: VFFamilyStyleWeight
# 需要導入模塊: from fontTools import ttLib [as 別名]
# 或者: from fontTools.ttLib import TTFont [as 別名]
def VFFamilyStyleWeight(path):
"""Extract family, style and weight from a variable font's name table.
Args:
path: Font path, eg ./fonts/ofl/lobster/Lobster[wght].ttf.
Returns:
FileFamilyStyleWeightTuple for file.
"""
with ttLib.TTFont(path) as font:
typoFamilyName = font['name'].getName(16, 3, 1, 1033)
familyName = font['name'].getName(1, 3, 1, 1033)
family = typoFamilyName.toUnicode() if typoFamilyName else \
familyName.toUnicode()
typoStyleName = font['name'].getName(17, 3, 1, 1033)
styleName = font['name'].getName(2, 3, 1, 1033)
style = typoStyleName.toUnicode() if typoStyleName else \
styleName.toUnicode()
style = "italic" if "Italic" in style.replace(" ", "") else "normal"
# For each font in a variable font family, we do not want to return
# the style's weight. We want to return 400 if 400 is within the
# the wght axis range. If it isn't, we want the value closest to 400.
weight = VFWeight(font)
return FileFamilyStyleWeightTuple(path, family, style, weight)
示例4: main
# 需要導入模塊: from fontTools import ttLib [as 別名]
# 或者: from fontTools.ttLib import TTFont [as 別名]
def main():
args = parser.parse_args()
headers = ['filename', 'usWeightClass']
rows = []
for font in args.font:
ttfont = ttLib.TTFont(font)
rows.append([os.path.basename(font), ttfont['OS/2'].usWeightClass])
def as_csv(rows):
import csv
import sys
writer = csv.writer(sys.stdout)
writer.writerows([headers])
writer.writerows(rows)
sys.exit(0)
if args.csv:
as_csv(rows)
print(tabulate.tabulate(rows, headers, tablefmt="pipe"))
示例5: main
# 需要導入模塊: from fontTools import ttLib [as 別名]
# 或者: from fontTools.ttLib import TTFont [as 別名]
def main():
args = parser.parse_args()
for font_path in args.fonts:
nametable = nametable_from_filename(font_path)
font = TTFont(font_path)
font_filename = ntpath.basename(font_path)
font['name'] = nametable
style = font_filename[:-4].split('-')[-1]
font['OS/2'].usWeightClass = set_usWeightClass(style)
font['OS/2'].fsSelection = set_fsSelection(font['OS/2'].fsSelection, style)
win_style = font['name'].getName(2, 3, 1, 1033).string.decode('utf_16_be')
font['head'].macStyle = set_macStyle(win_style)
font.save(font_path + '.fix')
print('font saved %s.fix' % font_path)
示例6: _CheckLSB0ForEmptyGlyphs
# 需要導入模塊: from fontTools import ttLib [as 別名]
# 或者: from fontTools.ttLib import TTFont [as 別名]
def _CheckLSB0ForEmptyGlyphs(path, font, ttf):
"""Checks if font has empty (loca[n] == loca[n+1]) glyphs that have non-0 lsb.
There is no reason to set such lsb's.
Args:
path: Path to directory containing font.
font: A font record from a METADATA.pb.
ttf: A fontTools.ttLib.TTFont for the font.
Returns:
A list of ResultMessageTuple for tests performed.
"""
results = []
if 'loca' not in ttf:
return results
for glyph_index, glyph_name in enumerate(ttf.getGlyphOrder()):
is_empty = ttf['loca'][glyph_index] == ttf['loca'][glyph_index + 1]
lsb = ttf['hmtx'][glyph_name][1]
if is_empty and lsb != 0:
results.append(
_SadResult(
'%s %s/%d [\'hmtx\'][\'%s\'][1] (lsb) should be 0 but is %d' %
(font.name, font.style, font.weight, glyph_name, lsb),
os.path.join(path, font.filename), _FixEmptyGlyphLsb(glyph_name)))
return results
示例7: ListFeatures
# 需要導入模塊: from fontTools import ttLib [as 別名]
# 或者: from fontTools.ttLib import TTFont [as 別名]
def ListFeatures(font):
"""List features for specified font. Table assumed structured like GPS/GSUB.
Args:
font: a TTFont.
Returns:
List of 3-tuples of ('GPOS', tag, name) of the features in the font.
"""
results = []
for tbl in ["GPOS", "GSUB"]:
if tbl in font.keys():
results += [
(tbl,
f.FeatureTag,
"lookups: [{}]".format(", ".join(map(str, f.Feature.LookupListIndex)))
) for f in font[tbl].table.FeatureList.FeatureRecord
]
return results
示例8: namelist_from_font
# 需要導入模塊: from fontTools import ttLib [as 別名]
# 或者: from fontTools.ttLib import TTFont [as 別名]
def namelist_from_font(file_name, out=None):
if out is None:
out = sys.stdout
excluded_chars = ["????", "SPACE", "NO-BREAK SPACE"]
font = TTFont(file_name)
charcodes = set()
for cmap in font["cmap"].tables:
if not cmap.isUnicode():
continue
charcodes.update(cp for cp,name in cmap.cmap.items())
charcodes = sorted(charcodes)
for charcode in charcodes:
hexchar, char, item_description = _format_codepoint(charcode)
if item_description not in excluded_chars:
string = "{} {} {}".format(hexchar, char, item_description)
print(string, file=out)
return
font.close()
示例9: _CheckFont
# 需要導入模塊: from fontTools import ttLib [as 別名]
# 或者: from fontTools.ttLib import TTFont [as 別名]
def _CheckFont(font):
"""Inspects a font for space/nbsp issues.
Args:
font: A TTFont.
Returns:
A set of strings describing problems found in the font. Empty set if none.
"""
problems = set()
(space_cmap, _) = _LoadGlyf(font, 0x0020, 'SPACE', problems)
(nbsp_cmap, _) = _LoadGlyf(font, 0x00A0, 'NBSP', problems)
if nbsp_cmap and _HasInk(font, nbsp_cmap):
problems.add('NBSP_HAS_INK')
if space_cmap and _HasInk(font, space_cmap):
problems.add('SPACE_HAS_INK')
if nbsp_cmap and space_cmap:
if font['hmtx'][nbsp_cmap][0] != font['hmtx'][space_cmap][0]:
problems.add('SPACE_NBSP_WIDTH_MISMATCH')
return set(problems)
示例10: printInfo
# 需要導入模塊: from fontTools import ttLib [as 別名]
# 或者: from fontTools.ttLib import TTFont [as 別名]
def printInfo(fonts, print_csv=False):
rows = []
headers = ['filename', 'fsSelection']
for font in fonts:
ttfont = ttLib.TTFont(font)
row = [os.path.basename(font)]
row.append(('{:#010b} '
'{:#010b}'
'').format(getByte2(ttfont),
getByte1(ttfont)).replace('0b', ''))
rows.append(row)
def as_csv(rows):
writer = csv.writer(sys.stdout)
writer.writerows([headers])
writer.writerows(rows)
sys.exit(0)
if print_csv:
as_csv(rows)
else:
print(tabulate.tabulate(rows, headers, tablefmt="pipe"))
示例11: main
# 需要導入模塊: from fontTools import ttLib [as 別名]
# 或者: from fontTools.ttLib import TTFont [as 別名]
def main(argv):
print(argv)
if len(argv) != 3:
raise ValueError('Specify two files to diff')
with warnings.catch_warnings():
warnings.simplefilter('ignore')
with open(argv[1], 'rb') as f1, open(argv[2], 'rb') as f2:
lhs = ttLib.TTFont(f1)
rhs = ttLib.TTFont(f2)
font_diff = _DiffFont(lhs, rhs)
for tag, one_side, diff_tuples, error in font_diff:
if error:
print('%s %s' % (tag, error))
elif one_side:
print('Only %s has %s' % (one_side.upper(), str(tag)))
elif not diff_tuples:
print('%s identical' % tag)
else:
print('%s DIFF' % tag)
for name, lhs, rhs in diff_tuples:
print(' %s %s != %s' % (name, _ShortDisplay(lhs), _ShortDisplay(rhs)))
示例12: main
# 需要導入模塊: from fontTools import ttLib [as 別名]
# 或者: from fontTools.ttLib import TTFont [as 別名]
def main(font_path):
filename = os.path.basename(font_path)
font = TTFont(font_path)
desired_style = style_parse(font)
current_weight_class = font["OS/2"].usWeightClass
updated = False
if current_weight_class != desired_style.usWeightClass:
print(f"{filename}: Updating weightClass to {desired_style.usWeightClass}")
font['OS/2'].usWeightClass = desired_style.usWeightClass
updated = True
# If static otf, update Thin and ExtraLight
# TODO (M Foley) fontbakery's style_parse should do this
if "CFF " in font and 'fvar' not in font:
if desired_style.usWeightClass == 100:
print(f"{filename}: Updating weightClass to {250}")
font['OS/2'].usWeightClass = 250
updated = True
elif desired_style.usWeightClass == 200:
print(f"{filename}: Updating weightClass to {275}")
font['OS/2'].usWeightClass = 275
updated = True
if updated:
font.save(font.reader.file.name + ".fix")
else:
print("{}: Skipping. Current WeightClass is correct".format(filename))
示例13: fix
# 需要導入模塊: from fontTools import ttLib [as 別名]
# 或者: from fontTools.ttLib import TTFont [as 別名]
def fix(fonts, value=None):
rows = []
headers = ['filename', 'usWidthClass was', 'usWidthClass now']
for font in fonts:
row = [font]
ttfont = ttLib.TTFont(font)
if not value:
usWidthClass = getFromFilename(font)
else:
usWidthClass = value
row.append(ttfont['OS/2'].usWidthClass)
ttfont['OS/2'].usWidthClass = usWidthClass
row.append(ttfont['OS/2'].usWidthClass)
ttfont.save(font + '.fix')
rows.append(row)
if rows:
print(tabulate.tabulate(rows, headers, tablefmt="pipe"))
示例14: _AxisInfo
# 需要導入模塊: from fontTools import ttLib [as 別名]
# 或者: from fontTools.ttLib import TTFont [as 別名]
def _AxisInfo(fontfile):
"""Gets variable axes info.
Args:
fontfile: Font file to look at for variation info
Returns:
Variable axes info
"""
with contextlib.closing(ttLib.TTFont(fontfile)) as font:
if 'fvar' not in font:
return frozenset()
else:
fvar = font['fvar']
axis_info = [
(a.axisTag, a.minValue, a.maxValue) for a in fvar.axes
]
return tuple(sorted(axis_info))
示例15: main
# 需要導入模塊: from fontTools import ttLib [as 別名]
# 或者: from fontTools.ttLib import TTFont [as 別名]
def main():
args = parser.parse_args()
rows = []
for font_filename in args.fonts:
font = TTFont(font_filename)
for field in font['name'].names:
enc = field.getEncoding()
rows.append([
('Font', ntpath.basename(font_filename)),
('platformID', field.platformID),
('encodingID', field.platEncID),
('languageID', field.langID),
('nameID', field.nameID),
('nameString', field.toUnicode()),
])
if args.csv:
printInfo(rows, save=True)
else:
printInfo(rows)