Created
March 9, 2012 19:54
-
-
Save vied12/2008331 to your computer and use it in GitHub Desktop.
Verify if given fonts are known and create an image to show them. Uses by default all the known fonts.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys, os | |
import cairo | |
import commands | |
def truncate_chars(value, max_length): # thanks django! | |
if len(value) <= max_length: | |
return value | |
truncd_val = value[:max_length] | |
if value[max_length] != " ": | |
rightmost_space = truncd_val.rfind(" ") | |
if rightmost_space != -1: | |
truncd_val = truncd_val[:rightmost_space] | |
return truncd_val + "..." | |
# == Main ================================= | |
image_path = os.path.abspath("test_font.png") | |
fonts = sys.argv[1:] | |
offset = 40 | |
known_fonts = [] | |
# get known fonts | |
out=commands.getoutput('fc-list').split('\n') | |
for line in out: | |
line = line.split(':style=') | |
font = line[0] | |
# styles = line[1].split(' ') | |
known_fonts.append(font) | |
_fonts = fonts or known_fonts | |
# init cairo | |
size = (1200, offset*len(_fonts)+offset) | |
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, size[0], size[1]) | |
ctx = cairo.Context(surface) | |
ctx.set_source_rgb(0,0,0) | |
ctx.set_font_size(30) | |
# background | |
ctx.set_source_rgb(255, 255, 255) | |
ctx.rectangle(0, 0, size[0], size[1]) | |
ctx.fill() | |
for i, font in enumerate(_fonts): | |
print "[%d] testing font %s" % (i+1, font) | |
# if tested font is provided by user, we check if fonts are known by the OS | |
if fonts: | |
unknown = False | |
if not font in known_fonts: | |
unknown = True | |
print "[%d]=====> font '%s' unknown !!" % (i+1, font) | |
# drawing line | |
if fonts and unknown: # colored in red if font is unknown | |
ctx.set_source_rgb(255, 0, 0) | |
ctx.rectangle(0, i*offset+0.25*offset, size[0], offset) | |
ctx.fill() | |
elif i%2: | |
ctx.set_source_rgba(0, 25, 25,0.2) | |
ctx.rectangle(0, i*offset+0.25*offset, size[0], offset) | |
ctx.fill() | |
ctx.set_source_rgb(0, 0, 0) | |
ctx.select_font_face("Courier new", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) | |
ctx.move_to(0, i*offset+offset) | |
ctx.show_text("%d %s" % (i+1, truncate_chars(font, 25))) | |
ctx.select_font_face(font, cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) | |
ctx.move_to(600, i*offset+offset) | |
ctx.show_text(font) | |
# write the image file | |
surface.write_to_png(image_path) | |
print "%d fonts tested" % len(_fonts) | |
print "image created at '%s'" % (image_path) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment