Text Alignment

Learn about text alignment in Pycairo.

We'll cover the following

Text alignment using text extent

We can use the text extents to align text. As an example, we will look at the ways to align text to the left, right, and center. Here is a function that displays a string that is left-aligned to the point (x, y):

def left_align(ctx, x, y, text):
    ctx.move_to(x, y)
    ctx.set_source_rgb(0, 0, 0)
    ctx.show_text(text)

This is fairly standard. It sets the current point to (x, y), sets the color to black, and then shows the text using the current font and size. The text is automatically left-aligned because that is Pycairo’s default alignment setting.

Here is the code to right-align text to the point (x, y):

def right_align(ctx, x, y, text):
    xbearing, ybearing, width, height, dx, dy = ctx.text_extents(text) 
    ctx.move_to(x - width, y)
    ctx.set_source_rgb(0, 0, 0)
    ctx.show_text(text)

In this case, we make an extra call to the text_extents function. The only value we are interested in is the width value.

We set the current point to (x - width, y). This means that the starting point of any text string depends on its width. It will always start at x-width, which means that the string will always end at (x, y).

Note: We only use the width value in this calculation. This assumes that the xbearing is zero (or negligible, at the very least). This is true of Latin characters, but might not necessarily be true of other writing systems.

We can also center-align text by setting the current point to (x - width/2, y):

def center_align(ctx, x, y, text):
    xbearing, ybearing, width, height, dx, dy = ctx.text_extents(text)
    ctx.move_to(x - width/2, y)
    ctx.set_source_rgb(0, 0, 0)
    ctx.show_text(text)

Here is an example of these three functions in action:

Get hands-on with 1200+ tech skills courses.