【问题标题】:cairo: show text by center-aligncairo:按中心对齐显示文本
【发布时间】:2012-09-11 09:12:33
【问题描述】:

我正在使用 C 语言的 gtk 中的 cairo 绘制图形。我使用cairo_show_text 来显示文本。为中心对齐定义中心点很容易。但我不知道如何使文本居中对齐。

问题是我不知道如何计算文本长度(我认为这也与字体大小有关)。如果我能得到文本长度,我可以使用cairo_move_to 移动到适当的点,然后通过cairo_show_text 显示文本。

有什么建议或其他方法吗?

根据后面的liberforce的评论,解决办法是

/* 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);
}

【问题讨论】:

    标签: text gtk alignment cairo


    【解决方案1】:

    看看cairo tutorial text alignment section

    请记住,对于文本,Cairo API 有点受限。对于更高级的东西,你需要pangocairo

    【讨论】:

    • 第一个链接中的提及确实有效。谢谢你。第二个链接,我没查,也说不出来。
    猜你喜欢
    • 2015-05-16
    • 2017-06-17
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 1970-01-01
    • 2015-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多