blob: 19fb8e03c198b38f0c732cf55d2a61f5b76b933a [file] [log] [blame]
Stephen M. Cameronee2f55b2012-03-27 08:14:09 +02001#include <cairo.h>
2#include <gtk/gtk.h>
3#include <math.h>
4
5static void draw_aligned_text(cairo_t *cr, const char *font, double x, double y,
6 double fontsize, const char *text, int alignment)
7{
8#define CENTERED 0
9#define LEFT_JUSTIFIED 1
10#define RIGHT_JUSTIFIED 2
11
12 double factor, direction;
13 cairo_text_extents_t extents;
14
Jens Axboe3c3ed072012-03-27 09:12:39 +020015 switch (alignment) {
Stephen M. Cameronee2f55b2012-03-27 08:14:09 +020016 case CENTERED:
17 direction = -1.0;
18 factor = 0.5;
19 break;
20 case RIGHT_JUSTIFIED:
21 direction = -1.0;
22 factor = 1.0;
23 break;
24 case LEFT_JUSTIFIED:
25 default:
26 direction = 1.0;
Stephen M. Cameronc3a5b6d2012-03-28 11:02:52 +020027 factor = 0.0;
Stephen M. Cameronee2f55b2012-03-27 08:14:09 +020028 break;
29 }
30 cairo_select_font_face(cr, font, CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
31
32 cairo_set_font_size(cr, fontsize);
33 cairo_text_extents(cr, text, &extents);
34 x = x + direction * (factor * extents.width + extents.x_bearing);
35 y = y - (extents.height / 2 + extents.y_bearing);
36
37 cairo_move_to(cr, x, y);
38 cairo_show_text(cr, text);
39}
40
41void draw_centered_text(cairo_t *cr, const char *font, double x, double y,
42 double fontsize, const char *text)
43{
44 draw_aligned_text(cr, font, x, y, fontsize, text, CENTERED);
45}
46
47void draw_right_justified_text(cairo_t *cr, const char *font,
48 double x, double y,
49 double fontsize, const char *text)
50{
51 draw_aligned_text(cr, font, x, y, fontsize, text, RIGHT_JUSTIFIED);
52}
53
54void draw_left_justified_text(cairo_t *cr, const char *font,
55 double x, double y,
56 double fontsize, const char *text)
57{
58 draw_aligned_text(cr, font, x, y, fontsize, text, LEFT_JUSTIFIED);
59}
60
Jens Axboe3c3ed072012-03-27 09:12:39 +020061void draw_vertical_centered_text(cairo_t *cr, const char *font, double x,
Stephen M. Cameronee2f55b2012-03-27 08:14:09 +020062 double y, double fontsize,
63 const char *text)
64{
65 double sx, sy;
66 cairo_text_extents_t extents;
67
68 cairo_select_font_face(cr, font, CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
69
70 cairo_set_font_size(cr, fontsize);
71 cairo_text_extents(cr, text, &extents);
72 sx = x;
73 sy = y;
74 y = y + (extents.width / 2.0 + extents.x_bearing);
75 x = x - (extents.height / 2.0 + extents.y_bearing);
76
77 cairo_move_to(cr, x, y);
78 cairo_save(cr);
79 cairo_translate(cr, -sx, -sy);
80 cairo_rotate(cr, -90.0 * M_PI / 180.0);
81 cairo_translate(cr, sx, sy);
82 cairo_show_text(cr, text);
83 cairo_restore(cr);
84}
85