BIV BIV - 16 days ago 5
C Question

Cairo, get width of monospaced latin character for surface

I have width & height in characters of future PNG, need draw exact fit picture.

int font_height=13, font_width=?;
cairo_surface_t *surface = cairo_image_surface_create(CAIRO_FORMAT_RGB24, font_width * pic_width_in_chars, font_height * pic_height_in_chars );
cairo_t *cr = cairo_create(surface);
cairo_select_font_face(cr, "Consolas", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
cairo_set_font_size( cr, font_height );
// fill surface by characters, no need help


For "–°onsolas" I picked manually proportion:
font_width = font_height * 3/5; But how to get it from API ?

Thanks, extents.x_advance is what I seek.

Answer

You can't do that, because the width of a single glyph is dependent on which character it is. You can compute the whole width adding the width of each one or using the whole string to do so.

In case of monospaced fonts, the width of any character is equal to the width of any other character. So if you compute one, you can multiply it by the number of characters in the string.

So the short answer is

  • There is no unit width for characters, except in monospaced fonts.

Using cairo_text_extents() can help quickly compute the width of the string. If it's a monospaced font, just use an arbitrary character and use it as the unit width.