欢迎关注公众号可以查看更多完整文章
Pango是一个开放源代码的自由函数库,用于高质量地渲染国际化的文字。Pango可以使用不同的后端字体,并提供了跨平台支持。
使用Pango显示文字,需要设置字体,因为需要使用字体去本地查找对应的字体文件,从而解析出正确的字型。
下面的示例是显示中文,设置字体为黑体,另外设置字体大小、显示位置等操作。
文字显示后保存到图片,并使用QT显示出来。
PangoFontDescription *font_description = pango_font_description_new();
pango_font_description_set_family(font_description, "simhei");//黑体
pango_font_description_set_weight(font_description, PANGO_WEIGHT_BOLD);
pango_font_description_set_absolute_size(font_description, 16 * PANGO_SCALE);//设置字体大小
pango_layout_set_font_description(layout, font_description);
std::wstring wstr = L"Pango是一个开放源代码的自由函数库,用于高质量地渲染国际化的文字。Pango可以使用不同的后端字体,并提供了跨平台支持。";
gchar *ch = g_utf16_to_utf8((gunichar2 *)wstr.c_str(), -1, NULL, NULL, NULL);//转成8位 Unicode码
pango_layout_set_text(layout, ch, -1);
//cairo_set_source_rgb(cr, 0.0, 1.0, 1.0);//设置字体颜色
cairo_move_to(cr, 10.0, 50.0);//显示位置
pango_cairo_show_layout_line(cr, pango_layout_get_line(layout, 0));//显示
如果显示高棉语Khmer或者泰语等需要组合的文字(Shaped Text),也是可以正确显示的,只需要把字体换成对应的字体名称,需要显示的文字当然也需要换成高棉语或者泰语。
当然,要显示高棉语或者泰语,还需要下载对应的字体文件,如果自己电脑上没有对应的字体的话。
需要依赖glib,pango,cairo等库。
示例代码:
#ifndef QSHOWTEXT_H
#define QSHOWTEXT_H
#include <QWidget>
class QSHowText : public QWidget
{
Q_OBJECT
public:
QSHowText(QWidget *parent = 0);
~QSHowText();
private:
};
#endif // QSHOWTEXT_H
#include "qshowtext.h"
#include "pango/pangocairo.h"
#include <QHBoxLayout>
#include <QLabel>
QSHowText::QSHowText(QWidget *parent)
: QWidget(parent)
{
cairo_surface_t *surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 1000, 500);
cairo_t *cr = cairo_create(surface);
PangoLayout *layout = pango_cairo_create_layout(cr);
PangoFontDescription *font_description = pango_font_description_new();
pango_font_description_set_family(font_description, "Khmer UI");//高棉语
pango_font_description_set_weight(font_description, PANGO_WEIGHT_BOLD);
pango_font_description_set_absolute_size(font_description, 16 * PANGO_SCALE);//设置字体大小
pango_layout_set_font_description(layout, font_description);
std::wstring wstr = L"Pango ជាបណ្ណាល័យប្រភពបើកចំហឥតគិតថ្លៃសម្រាប់បង្ហាញអត្ថបទដែលអន្ដរជាតិដែលមានគុណភាពខ្ពស់។ Pango អាចប្រើកម្មវិធីខាងក្រោយពុម្ពអក្សរផ្សេងគ្នានិងផ្តល់ការគាំទ្រឆ្លងវេទិកា។";
gchar *ch = g_utf16_to_utf8((gunichar2 *)wstr.c_str(), -1, NULL, NULL, NULL);//转成8位 Unicode码
pango_layout_set_text(layout, ch, -1);
//cairo_set_source_rgb(cr, 0.0, 1.0, 1.0);//设置字体颜色
cairo_move_to(cr, 10.0, 50.0);//显示位置
pango_cairo_show_layout_line(cr, pango_layout_get_line(layout, 0));//显示
g_object_unref(layout);
pango_font_description_free(font_description);
QString strImage = "test.png";
cairo_surface_write_to_png(cairo_get_target(cr), strImage.toStdString().c_str());
QLabel *pLabel = new QLabel(this);
pLabel->setPixmap(QPixmap(strImage));
QHBoxLayout* pHBox = new QHBoxLayout(this);
pHBox->addWidget(pLabel);
}
QSHowText::~QSHowText()
{
}