pango.c (2499B)
1 #include <cairo/cairo.h> 2 #include <pango/pangocairo.h> 3 #include <stdbool.h> 4 #include <stdio.h> 5 #include <stdlib.h> 6 #include <string.h> 7 8 #include "pango.h" 9 10 int get_font_height(const char *fontstr) { 11 PangoFontMap *fontmap = pango_cairo_font_map_get_default(); 12 PangoContext *context = pango_font_map_create_context(fontmap); 13 PangoFontDescription *desc = pango_font_description_from_string(fontstr); 14 PangoFont *font = pango_font_map_load_font(fontmap, context, desc); 15 if (font == NULL) { 16 pango_font_description_free(desc); 17 g_object_unref(context); 18 return -1; 19 } 20 PangoFontMetrics *metrics = pango_font_get_metrics(font, NULL); 21 int height = pango_font_metrics_get_height(metrics) / PANGO_SCALE; 22 pango_font_metrics_unref(metrics); 23 g_object_unref(font); 24 pango_font_description_free(desc); 25 g_object_unref(context); 26 return height; 27 } 28 29 PangoLayout *get_pango_layout(cairo_t *cairo, const char *font, 30 const char *text, double scale) { 31 PangoLayout *layout = pango_cairo_create_layout(cairo); 32 PangoAttrList *attrs = pango_attr_list_new(); 33 pango_layout_set_text(layout, text, -1); 34 pango_attr_list_insert(attrs, pango_attr_scale_new(scale)); 35 PangoFontDescription *desc = pango_font_description_from_string(font); 36 pango_layout_set_font_description(layout, desc); 37 pango_layout_set_single_paragraph_mode(layout, 1); 38 pango_layout_set_attributes(layout, attrs); 39 pango_font_description_free(desc); 40 pango_attr_list_unref(attrs); 41 return layout; 42 } 43 44 void get_text_size(cairo_t *cairo, const char *font, int *width, int *height, 45 int *baseline, double scale, const char *text) { 46 PangoLayout *layout = get_pango_layout(cairo, font, text, scale); 47 pango_cairo_update_layout(cairo, layout); 48 pango_layout_get_pixel_size(layout, width, height); 49 if (baseline) { 50 *baseline = pango_layout_get_baseline(layout) / PANGO_SCALE; 51 } 52 g_object_unref(layout); 53 } 54 55 int text_width(cairo_t *cairo, const char *font, const char *text) { 56 int text_width; 57 get_text_size(cairo, font, &text_width, NULL, NULL, 1, text); 58 return text_width; 59 } 60 61 void pango_printf(cairo_t *cairo, const char *font, double scale, 62 const char *text) { 63 PangoLayout *layout = get_pango_layout(cairo, font, text, scale); 64 cairo_font_options_t *fo = cairo_font_options_create(); 65 cairo_get_font_options(cairo, fo); 66 pango_cairo_context_set_font_options(pango_layout_get_context(layout), fo); 67 cairo_font_options_destroy(fo); 68 pango_cairo_update_layout(cairo, layout); 69 pango_cairo_show_layout(cairo, layout); 70 g_object_unref(layout); 71 }