使用Perl Pango进行文本对齐

3

我使用了Perl中的Pango,并成功地完美呈现了从右到左的文本(这个任务真是噩梦):

代码:

#!/usr/bin/perl -wT

use strict;
use warnings;
use Pango;
use Encode;

my $surface = Cairo::ImageSurface->create('argb32', 400, 100);
my $cr      = Cairo::Context->create($surface);
my $layout  = Pango::Cairo::create_layout($cr);

my $text    = decode('utf8','测试');
$layout->set_text("$text");

my $font    = Pango::FontDescription->from_string ('Serif Bold 50');
$layout->set_font_description($font);

Pango::Cairo::show_layout($cr, $layout);

$surface->write_to_png('pango.png');

然而,我遇到的唯一问题是文本对齐。我不知道如何使文本居中。我阅读了Pango文档,但没有找到太多信息。有人知道怎么做吗?
1个回答

2
基于我对文档的阅读,我会说使用$layout->set_alignment('center');来进行布局,但我没有使用过Pango也没有尝试过。
而且,似乎布局的默认大小紧密地包裹内容,所以要让居中对齐起作用,您需要将布局的宽度设置为允许其发生的某些值,例如- $layout->set_width(400)编辑 添加set_width()段落。

谢谢AFresh1,我之前尝试过使用“set_alignment”,但由于某些原因文本对齐方式没有改变,仍然保持不变。 - user1129665
@Barakat 或许布局的默认宽度紧贴文本而不是适应图像表面,你需要 $layout->set_width(400) 吗? - AFresh1
非常感谢!现在有些变化。文本已经移动了。我只需要修复布局位置,因为一半的文本在图像外面。 - user1129665

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接