Text cairo:按中心对齐显示文本

Text cairo:按中心对齐显示文本,text,gtk,alignment,cairo,Text,Gtk,Alignment,Cairo,我正在用C语言的gtk用cairo绘制一个图形。我用cairo\u show\u text来显示文本。定义“中心对齐”的中心点很容易。但我不知道如何使文本中心对齐 问题是我不知道如何计算文本长度(我想这也是关于字体大小的问题)。如果我可以获得文本长度,我可以使用cairo\u move\u to移动到适当的位置,然后通过cairo\u show\u text显示文本 有什么建议或其他方法吗 根据自由部队的评论,解决办法是 /* howto_move: 0 -- cairo_move_to, 1

我正在用C语言的gtk用cairo绘制一个图形。我用
cairo\u show\u text
来显示文本。定义“中心对齐”的中心点很容易。但我不知道如何使文本中心对齐

问题是我不知道如何计算文本长度(我想这也是关于字体大小的问题)。如果我可以获得文本长度,我可以使用
cairo\u move\u to
移动到适当的位置,然后通过
cairo\u show\u text
显示文本

有什么建议或其他方法吗

根据自由部队的评论,解决办法是

/* 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);
}
看这张照片


请记住,对于文本,cairoapi有点有限。对于更高级的内容,您需要。

第一个链接中提到的内容确实有效。非常感谢。对于第二个链接,我没有检查,也说不出来。