[cairo-commit] [cairo-www] src/pycairo_pango.mdwn
Carl Worth
cworth at freedesktop.org
Wed Mar 23 23:42:05 PDT 2011
src/pycairo_pango.mdwn | 62 +++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 62 insertions(+)
New commits:
commit cfeace6eca836aaaeb2a47741bc1b4b25a53a55f
Author: JoaoBueno <JoaoBueno at web>
Date: Wed Mar 23 23:42:05 2011 -0700
creation
diff --git a/src/pycairo_pango.mdwn b/src/pycairo_pango.mdwn
new file mode 100644
index 0000000..43faa9b
--- /dev/null
+++ b/src/pycairo_pango.mdwn
@@ -0,0 +1,62 @@
+## Rendering fonts with Python
+((c) João S. O. Bueno. Code licence: CreativeCommons BY 3.0)
+
+Using "helvetica" or "sans" fonts with Cairo only is easy with the
+"toyfont" api provided. However, for serious font work, one gets trapped
+as FreeType engine is not implemented. To the rescue, comes pango, and pangocairo -
+pango is a library created with the sole purpose of high quality text rendering.
+
+Documentation on using pango along with cairo is scarce, and most examples are in C,
+- and those don't map straight into Python.
+
+My system has all the libraries available - I suppose pangocairo comes along with
+the python-pango bindings.
+
+The snippet bellow can render a sample text in a given font family,
+that can be specified as a command line parameter. It also prints
+the available font families to stdout.
+
+
+ # -*- coding: utf-8 -*-
+ import cairo
+ import pango
+ import pangocairo
+ import sys
+
+ surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 320, 120)
+ context = cairo.Context(surf)
+
+ #draw a background rectangle:
+ context.rectangle(0,0,320,120)
+ context.set_source_rgb(1, 1, 1)
+ context.fill()
+
+ #get font families:
+
+ font_map = pangocairo.cairo_font_map_get_default()
+ families = font_map.list_families()
+
+ # to see family names:
+ print [f.get_name() for f in font_map.list_families()]
+
+ #context.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
+
+ # Translates context so that desired text upperleft corner is at 0,0
+ context.translate(50,25)
+
+ pangocairo_context = pangocairo.CairoContext(context)
+ pangocairo_context.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
+
+ layout = pangocairo_context.create_layout()
+ fontname = sys.argv[1] if len(sys.argv) >= 2 else "Sans"
+ font = pango.FontDescription(fontname + " 25")
+ layout.set_font_description(font)
+
+ layout.set_text(u"Hello World")
+ context.set_source_rgb(0, 0, 0)
+ pangocairo_context.update_layout(layout)
+ pangocairo_context.show_layout(layout)
+
+ with open("cairo_text.png", "wb") as image_file:
+ surf.write_to_png(image_file)
+
More information about the cairo-commit
mailing list