本文介绍了正在将字体从文件加载到Pango吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码使用开罗 Pango 来创建图片:

I have a code uses Cairo and Pango to create an image :

#include<stdio.h>
#include<cairo.h>
#include<pango/pangocairo.h>

#define IMAGE_WIDTH  650
#define IMAGE_HEIGHT 150

#define TEXT "HELLO WORLD"
#define FONT "MizuFontAlphabet Normal 40"

/*
 * $ gcc $(pkg-config pangocairo cairo --cflags --libs) file.c
 */


int main(int argc , char** argv) {

    cairo_surface_t *surface;
    cairo_t *cr;

    PangoLayout *layout;
    PangoFontDescription *desc;
    PangoRectangle extents;

    surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, IMAGE_WIDTH, IMAGE_HEIGHT);
    cr      = cairo_create(surface);

    cairo_rectangle(cr, 0, 0, IMAGE_WIDTH, IMAGE_HEIGHT);
    cairo_set_source_rgb(cr, 0, 0, 0);
    cairo_fill(cr);
    cairo_stroke(cr);

    /* the font is needed to be installed in fonts directory */
    layout  = pango_cairo_create_layout(cr);
    pango_layout_set_text(layout, TEXT, -1);
    desc    = pango_font_description_from_string(FONT);
    pango_layout_set_font_description(layout, desc);
    pango_font_description_free (desc);

    pango_layout_get_pixel_extents(layout, NULL, &extents);
    int x   = (int) (IMAGE_WIDTH - extents.width) / 2;
    int y   = (int) (IMAGE_HEIGHT - extents.height) / 2;

    cairo_set_source_rgb(cr, 0.33, 0.55, 0.88);
    cairo_move_to(cr, x, y);
    pango_cairo_show_layout(cr, layout);

    g_object_unref(layout);

    cairo_surface_write_to_png(surface, "image.png");

    cairo_destroy(cr);
    cairo_surface_destroy(surface);

    return(0);
}

我使用的字体 MizuFontAlphabet 是非标准字体,因此需要将其安装在fonts目录中,以便可以与Pango一起使用:

The font I use , MizuFontAlphabet, is a none-standard font so it is needed to be installed in the fonts directory so I can use it with Pango :

    desc    = pango_font_description_from_string(FONT);

如果未安装字体,如何从文件中加载字体?

How could I load the font from a file in case that font wasn't installed?

推荐答案

通过向本地fontconfig状态添加自定义字体,可以很容易地解决此问题:

This problem can be solved fairly easily by adding a custom font to the local fontconfig state:

#include <fontconfig/fontconfig.h>


std::string yourFontFilePath = "/home/testUser/bla.ttf";
const FcChar8 * file = (const FcChar8 *)yourFontFilePath.c_str();
FcBool fontAddStatus = FcConfigAppFontAddFile(FcConfigGetCurrent(), file);

现在,pango渲染引擎将仅通过使用PangoFontDescription来使用您的自定义字体.

Now the pango rendering engine will use your custom font just by using the PangoFontDescription.

这篇关于正在将字体从文件加载到Pango吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-03 09:15