5

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?

Kevin Thibedeau
  • 3,299
  • 15
  • 26

1 Answers1

5

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)
Kevin Thibedeau
  • 3,299
  • 15
  • 26
  • 2
    "The Pango context (now Pango.Context) is retrieved from the Pango.Layout object now." This is not the reason why your solution works. "pctx = PangoCairo.create_context(ctx)" will work the same way. You changed the code that sets antialiasing. – beroal Feb 26 '17 at 18:18