warem
warem

Reputation: 1683

cairo: show text by center-align

I am drawing a graph using cairo in gtk of C language. I used cairo_show_text to show text. It is easy to define the center point for center-align. But I didn't know how to make the text center-align.

The problem is that I don't know how to calculate text length(It is also concerning about font size I think). If I can get the text legth, I can move to the appropriate point by using cairo_move_to and then show the text by cairo_show_text.

Any suggestion or any other approach?

According to the followed liberforce's comment, the solution is

/* howto_move: 0 -- cairo_move_to, 1 -- cairo_rel_move_to
 * x, y is the coordinate of the point for center-align. Whether it is absolute
 * or relative coordinate depends on `howto_move'
 */
void cairo_text_align_horizontal_center (cairo_t *cr, char *text, int if_vertical, int howto_move, double x, double y)
{
  cairo_text_extents_t te;
  double new_x, new_y;

  cairo_text_extents(cr, text, &te);
  if(!if_vertical)
  {
    new_x = x - (te.x_bearing + te.width / 2);
    new_y = y;
  }
  else
  {
    new_x = x;
    new_y = y + (te.x_bearing + te.width / 2);
  }
  if(howto_move == 0)
    cairo_move_to(cr, new_x, new_y);
  else
    cairo_rel_move_to(cr, new_x, new_y);
  cairo_save(cr);
  if(!if_vertical)
    cairo_rotate(cr, 0);
  else
    cairo_rotate(cr, - PI / 2.0);
  cairo_show_text(cr, text);
  cairo_restore(cr);
  cairo_stroke(cr);
}

Upvotes: 2

Views: 5022

Answers (1)

liberforce
liberforce

Reputation: 11454

Look at the cairo tutorial text alignment section.

Keep in mind that for text, the Cairo API is a bit limited. For more advanced stuff, you'll need pangocairo.

Upvotes: 2

Related Questions