Skip to content

Instantly share code, notes, and snippets.

@olymk2
Created May 4, 2015 14:59
Show Gist options
  • Save olymk2/4effe13df43cd3381a7f to your computer and use it in GitHub Desktop.
Save olymk2/4effe13df43cd3381a7f to your computer and use it in GitHub Desktop.
import os
import sys
from PIL import Image
from cairo import FontOptions, SVGSurface, ImageSurface, Context, Matrix
from cairo import FORMAT_ARGB32, FONT_SLANT_NORMAL, FONT_WEIGHT_BOLD, ANTIALIAS_SUBPIXEL, LINE_JOIN_ROUND
from gi.repository import Pango
from gi.repository import PangoCairo
class vector_atlas:
data = None
data_text = None
width = 512
height = 512
texture_id = None
text_texture_id = None
surface = None
draw = None
pango_draw = None
def __init__(self):
self.data = None
self.data_text = None
self.width = 512
self.height = 512
self.texture_id = None
self.text_texture_id = None
self.surface = None
self.draw = None
self.pango_draw = None
def setup(self, size=512):
self.width = size
self.height = size
self.surface = ImageSurface(FORMAT_ARGB32, size, size)
self.draw = Context(self.surface)
self.draw.scale(1, 1)
self.draw.set_source_rgb(0.0, 0.0, 0.0)
def cairo_to_pil(self):
return Image.frombuffer(
'RGBA', (self.width, self.height),
self.surface.get_data(), 'raw', 'BGRA', 0, 1
).tostring('raw', 'RGBA', 0, -1)
def available_fonts(self):
font_map = PangoCairo.cairo_font_map_get_default()
families = font_map.list_families()
print([f.get_name() for f in font_map.list_families()])
def text_atlas(self, text, fontname='Monospace', font_size = 48, size=512):
filename = './atlas' + str(size) + 'x' + str(size) + '.png'
self.setup()
layout = PangoCairo.create_layout(self.draw)
font = Pango.FontDescription(fontname + " " + str(font_size))
font_options = FontOptions()
font_options.set_antialias(ANTIALIAS_SUBPIXEL)
layout.set_font_description(font)
width, height = layout.get_size()
x_pos = 0
y_pos = 0
layout.set_height(64)
self.draw.move_to(x_pos, y_pos)
for letter in text:
layout.set_text(letter, -1)
self.draw.set_source_rgb(0, 0, 0)
PangoCairo.update_layout(self.draw, layout)
self.draw.move_to(x_pos, y_pos)
PangoCairo.show_layout(self.draw, layout)
x_pos += font_size
if x_pos + font_size > size:
x_pos = 0
y_pos += font_size
self.surface.write_to_png(filename)
v = vector_atlas()
v.text_atlas('y0123456789+-%xyz')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment