为什么 `pango_layout_get_pixel_extents` 会返回一个0×2的矩形?

编程语言 2026-07-10

我几乎按照 the tutorial 中描述的流程来与PangoCairo交互,唯一的区别是我在构造函数之外的一个函数里设置字体大小(因为我想创建一个可以接受任意字体大小的函数):

#include <stdio.h>

#include <cairo/cairo.h>

#include <pango/pangocairo.h>

int main() {
    cairo_surface_t *const surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 400, 400);
    cairo_t *const cairo = cairo_create(surface);
    PangoContext *const pango = pango_cairo_create_context(cairo);
    PangoFontDescription *desc = pango_font_description_from_string("Noto Sans Regular");
    PangoLayout *layout = pango_layout_new(pango);

    pango_layout_set_text(layout, "Hello, world!", 13);
    pango_font_description_set_size(desc, 16);
    pango_layout_set_font_description(layout, desc);

    PangoRectangle lay_rect, px_rect;
    pango_layout_get_extents(layout, nullptr, &lay_rect);
    pango_layout_get_pixel_extents(layout, nullptr, &px_rect);
    printf(
        "{\n"
        "\t\"lw\": %i,\n"
        "\t\"lh\": %i,\n"
        "\t\"pw\": %i,\n"
        "\t\"ph\": %i\n"
        "}\n",
        lay_rect.width,
        lay_rect.height,
        px_rect.width,
        px_rect.height
    );
    return 0;
}

为什么这会让布局把它当成0×2,应该如何修复?

解决方案

Pango使用的单位是点的 1/1024。传入 16 意味着你在设置大约0.016pt的字体大小,基本不可见

修复:

pango_font_description_set_size(desc, 16 * PANGO_SCALE);
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章