[cairo] Fitting Text To A Given Width
ldo at geek-central.gen.nz
Fri Dec 30 23:08:35 UTC 2016
I have been adding some code to my Qahirah Notebooks
<https://github.com/ldo/qahirah_notebooks> demonstrating how to fit
text to a given width (in the “Beginning Text” notebook). The example
uses a list of text items of wildly differing width, so no single font
size looks best for all. Instead, I apply a non-uniform scaling to the
text to make it fit.
The core of the (Python) code looks like this:
ctx.font_matrix = uniform_font_matrix
text_width = ctx.text_extents(item).advance.x
if text_width > fit_width :
ctx.font_matrix = Matrix.scale((fit_width / text_width, 1)) * uniform_font_matrix
However, if you try the notebook, you will see that the lines frequently
come out too wide or too narrow. I tried playing with the
HINT_STYLE_xxx and HINT_METRICS_xxx font options, but these didn’t seem
What did work was to do it in a more complex way: render the text to a
separate ImageSurface with uniform scaling, then apply nonuniform
scaling to that as a pattern to render it back to the final image. This
gives me much more consistent results.
Is there some rounding going on in the text rendering?
More information about the cairo