glpangofont.c 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*************************************************************************
  2. * Copyright (c) 2011 AT&T Intellectual Property
  3. * All rights reserved. This program and the accompanying materials
  4. * are made available under the terms of the Eclipse Public License v1.0
  5. * which accompanies this distribution, and is available at
  6. * https://www.eclipse.org/legal/epl-v10.html
  7. *
  8. * Contributors: Details at https://graphviz.org
  9. *************************************************************************/
  10. #include <glcomp/glpangofont.h>
  11. #include <stdlib.h>
  12. static PangoLayout *get_pango_layout(char *markup_text,
  13. char *fontdescription, int fontsize,
  14. double *width, double *height)
  15. {
  16. PangoFontMap *fontmap;
  17. PangoLayout *layout;
  18. int pango_width, pango_height;
  19. char *text;
  20. PangoAttrList *attr_list;
  21. fontmap = pango_cairo_font_map_get_default();
  22. if (!pango_parse_markup
  23. (markup_text, -1, '\0', &attr_list, &text, NULL, NULL))
  24. return NULL;
  25. PangoContext *const context = pango_font_map_create_context(fontmap);
  26. layout = pango_layout_new(context);
  27. g_object_unref(context);
  28. pango_layout_set_text(layout, text, -1);
  29. free(text);
  30. PangoFontDescription *const desc =
  31. pango_font_description_from_string(fontdescription);
  32. pango_font_description_set_size(desc, (int)(fontsize * PANGO_SCALE));
  33. pango_layout_set_font_description(layout, desc);
  34. pango_layout_set_attributes(layout, attr_list);
  35. pango_attr_list_unref(attr_list);
  36. pango_font_description_free(desc);
  37. pango_layout_set_alignment(layout, PANGO_ALIGN_CENTER);
  38. pango_layout_get_size(layout, &pango_width, &pango_height);
  39. *width = (double) pango_width / PANGO_SCALE;
  40. *height = (double) pango_height / PANGO_SCALE;
  41. return layout;
  42. }
  43. unsigned char *glCompCreatePangoTexture(char *fontdescription, int fontsize,
  44. char *txt, cairo_surface_t **surface,
  45. int *w, int *h) {
  46. PangoLayout *layout;
  47. double width, height;
  48. *surface = NULL;
  49. layout =
  50. get_pango_layout(txt, fontdescription, fontsize, &width, &height);
  51. if (layout == NULL) {
  52. return NULL;
  53. }
  54. //create the right size canvas for character set
  55. *surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, (int)width,
  56. (int) height);
  57. cairo_t *cr = cairo_create(*surface);
  58. //set pen color to white
  59. cairo_set_source_rgba(cr, 1, 1, 1, 1);
  60. //draw the text
  61. pango_cairo_show_layout(cr, layout);
  62. *w = (int) width;
  63. *h = (int) height;
  64. g_object_unref(layout);
  65. cairo_destroy(cr);
  66. return cairo_image_surface_get_data(*surface);
  67. }