Move Cairo layout creation and display code to two separate functions

This effectively splits the imv_canvas_printf function into two separate
functions, one to create a layout containing given text and the other one
to show it on the canvas. These functions can be useful for the future code
I will add to display text with a background rectangle behind it. Existing
imv_canvas_printf function does not allow this
This commit is contained in:
Ivan Oleynikov 2021-09-18 02:56:58 +02:00 committed by Harry Jeffery
parent 4690692154
commit a810b71f14
2 changed files with 29 additions and 5 deletions

View file

@ -180,6 +180,22 @@ void imv_canvas_font(struct imv_canvas *canvas, const char *name, int size)
pango_font_description_set_size(canvas->font, size * PANGO_SCALE);
}
PangoLayout *imv_canvas_make_layout(struct imv_canvas *canvas, const char *line)
{
PangoLayout *layout = pango_cairo_create_layout(canvas->cairo);
pango_layout_set_font_description(layout, canvas->font);
pango_layout_set_text(layout, line, -1);
return layout;
}
void imv_canvas_show_layout(struct imv_canvas *canvas, int x, int y,
PangoLayout *layout)
{
cairo_move_to(canvas->cairo, x, y);
pango_cairo_show_layout(canvas->cairo, layout);
}
int imv_canvas_printf(struct imv_canvas *canvas, int x, int y, const char *fmt, ...)
{
char line[1024];
@ -187,12 +203,9 @@ int imv_canvas_printf(struct imv_canvas *canvas, int x, int y, const char *fmt,
va_start(args, fmt);
vsnprintf(line, sizeof line, fmt, args);
PangoLayout *layout = pango_cairo_create_layout(canvas->cairo);
pango_layout_set_font_description(layout, canvas->font);
pango_layout_set_text(layout, line, -1);
PangoLayout *layout = imv_canvas_make_layout(canvas, line);
cairo_move_to(canvas->cairo, x, y);
pango_cairo_show_layout(canvas->cairo, layout);
imv_canvas_show_layout(canvas, x, y, layout);
PangoRectangle extents;
pango_layout_get_pixel_extents(layout, NULL, &extents);

View file

@ -3,6 +3,8 @@
#include <stdbool.h>
#include <pango/pangocairo.h>
struct imv_canvas;
struct imv_image;
@ -41,6 +43,15 @@ void imv_canvas_fill_checkers(struct imv_canvas *canvas, struct imv_image *image
/* Select the font to draw text with */
void imv_canvas_font(struct imv_canvas *canvas, const char *name, int size);
/* Prepare layout containing the given string, ready for rendering on the given
* canvas. The caller is responsible for releasing it with a call to
* g_object_unref */
PangoLayout *imv_canvas_make_layout(struct imv_canvas *canvas, const char *str);
/* Shows layout with at the specified coordinates */
void imv_canvas_show_layout(struct imv_canvas *canvas, int x, int y,
PangoLayout *layout);
/* Draw some text on the canvas, returns the width used in pixels */
int imv_canvas_printf(struct imv_canvas *canvas, int x, int y, const char *fmt, ...);