Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PangoCairo with PyGObject API

I am porting a Python2 script that uses Pango for drawing text to a Cairo surface. It works fine using the old PyGtk API with the pangocairo package. My system (Debian Jesse) doesn't have Python3 packages for PyGtk and instead uses the newer Gtk+ libraries with the PyGObject API.

I want to create a pangocairo.CairoContext object but it seems to be missing in the new API. The PangoCairo package has a create_context() function but it generates a PangoContext object that doesn't have the methods I need.

So far I have this:

import cairo
from gi.repository import Pango
from gi.repository import PangoCairo

surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 8, 8)
ctx = cairo.Context(surf)
pctx = PangoCairo.create_context(ctx) # Creates a PangoContext
pctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL) # This fails

The old Python2 code that works:

import cairo
import pango
import pangocairo

surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 8, 8)
ctx = cairo.Context(surf)
pctx = pangocairo.CairoContext(ctx)
pctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL)

Does anyone have a solution for this? Is there any good documentation on how PangoCairo should be used with the new API?

like image 820
Kevin Thibedeau Avatar asked Oct 22 '16 16:10

Kevin Thibedeau


1 Answers

It looks like the library has been rearranged a bit. The Pango context (now Pango.Context) is retrieved from the Pango.Layout object now. Here is a working solution:

import cairo
from gi.repository import Pango
from gi.repository import PangoCairo

surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 8, 8)
ctx = cairo.Context(surf)
layout = PangoCairo.create_layout(ctx)
pctx = layout.get_context()

fo = cairo.FontOptions()
fo.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
PangoCairo.context_set_font_options(pctx, fo)
like image 97
Kevin Thibedeau Avatar answered Nov 03 '22 09:11

Kevin Thibedeau