Measuring text outside the drawing function

In order to request the size for a custom widget, i need to find some text size. To get text sizes, you need a cairo_t context which is only available while drawing. So how do i measure text during a layout phase?

To get text sizes, you need a cairo_t context

I don’t think this is necessary, nor that it makes much sense. Cairo is involved in the final step drawing text, not preparing it. You probably want to look into Pango instead, e.g. Pango.Layout.get_pixel_size(), Pango.Layout.get_pixel_extents() et al.

For instance, there is Gtk.Label.get_layout() if your custom widget contains labels whose text you need to measure, or if not then probably you are (or should be!) using Pango.Layout directly - and can use the available methods via either of these routes.

If you create a layout object using pango_cairo_create_layout you need Cairo. Even if you don’t use Cairo to create a layout, you need to apply the transformations that the Cairo context uses in the drawing function.

You don’t create PangoLayout instances in GTK by calling pango_cairo_create_layout() directly: you use gtk_widget_create_pango_layout().

My widgets are “virtual”. They live inside a Gtk widget and only get a Cairo context. But however you get the layout, then you need a “cr” to call pango_cairo_update_layout as shown here:

I have no idea what that means.

If you have a widget, and you’re measuring/rendering text using PangoLayout, then you have to create PangoLayout instances using gtk_widget_create_pango_layout(). Once you have a PangoLayout, you can keep it around for as long as you like, and use it for measuring text, or rendering it by using PangoCairo or the text rendering API in GTK.

1 Like

It means that my “virtual” widgets are not part of Gtk. It’s my own widget system.

My concern is this: if i measure some text with a layout and the drawing function renders the same text in a Cairo context that’s transformed (scaled for example) the size of the measured text differs from the one drawn. So i’m afraid that the rendering of the text, might be altered by some setting in the Cairo context, that the layout object is not aware of.

Is gtk_widget_create_pango_layout() multithread safe?

Rendering large texts can be slow, so preparing and rendering into a texture it in a background thread should be possible.

What if i don’t know which widget i will later use it on? What if i want to use it into 2 different widgets at the same time? Skia/DirectWrite/OpenText/Qt all allow this. pango_cairo_create_layout needs to be useable.

As a rule, everything GTK must happen in the main thread.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.