[cairo] How to measure Fonts

Kalle Vahlman kalle.vahlman at gmail.com
Mon Feb 5 00:44:00 PST 2007


2007/2/5, thom_schu at gmx.de <thom_schu at gmx.de>:
> Hi there,
> I want to draw my own Gtkmm-Widgets using Pango + Cairo.
> I started to draw some lines, rectangles ..... everything looked fine.
> But then I started to work with fonts and I got confused.
>
> What I wanted to do is to draw a Rectangle and put a String in the
> y-middle of that Rectangle :
>
> cairoContext->rectangle(0, 0, 200, 20);
> cairoContext->fill();
> Cairo::TextExtents extents;
> cairoContext->get_text_extents("HELLO", extents);
> cairoContext->move_to(0, 20-((20-extents.height)/2));
> cairoContext->show_text("HELLO");
>
> But this doesnt work at all. The font-height is smaller then the value of extends.height.
> I also tried with "pangoLayout->get_pixel_size( ....), but get the same result.

I'm not sure what the cairo API for text does here, but it's generally
better to use Pango API for text layout and drawing (and since this is
for GTK+, doubly so).

I think that in the move_to(), your calculation is a bit wrong. For
example, for a font height of 10 pixels, it will end up in 15, while
you'll want it to be 5. You should first take the half of the height
of the rectangle (20/2) and then substract half of the height of the
font (extents.height/2) to get it on the correct level. So:

  cairoContext->move_to(0, (20/2)-(extents.height/2));

should take the current point to where you want it to be.

> I think all this font-stuff is too much for me.
> Isnt there an introduction ?
> Why does the font look different when I draw with a gtk-draw-method like
> window->draw_layout(...) or with
> pangoLayout->get_line(0)->show_in_cairo_context(cairoContext),
> the Cairo::Context was created with window->create_cairo_context() ......

It depends where the Pango layout is created from (as that's what
defines the used font). draw_layout() creates the layout from the
widget, using the style settings for it (including font), while if you
just create a layout "from nothing" and draw that, it'll use the
default font (whatever that happens to be).

Use widget->create_pango_layout("text") to get a layout that uses the
font set in GTK+ theme.

-- 
Kalle Vahlman, zuh at iki.fi
Powered by http://movial.fi
Interesting stuff at http://syslog.movial.fi


More information about the cairo mailing list