Created
June 20, 2019 11:51
-
-
Save ross-newman/6d0346859e500c3cfe2d46acf77b4a1a to your computer and use it in GitHub Desktop.
Cairo text alignment using cairo_text_extents
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cairo.h> | |
// gcc main.cpp -o test $(pkg-config cairo --cflags) $(pkg-config cairo --libs) $(pkg-config --cflags gtk+-3.0) $(pkg-config --libs gtk+-3.0) | |
#include <cairo.h> | |
#include <gtk/gtk.h> | |
static void do_drawing(cairo_t *, int align); | |
static gboolean on_draw_event(GtkWidget *widget, cairo_t *cr, | |
gpointer user_data) | |
{ | |
do_drawing(cr, 1); | |
do_drawing(cr, 2); | |
do_drawing(cr, 3); | |
return FALSE; | |
} | |
#define TEXT "Knowledge is power" | |
static void do_drawing(cairo_t *cr, int align) | |
{ | |
cairo_text_extents_t extends; | |
cairo_set_source_rgb(cr, 0, 0, 0); | |
cairo_select_font_face(cr, "Courier", CAIRO_FONT_SLANT_NORMAL, | |
CAIRO_FONT_WEIGHT_NORMAL); | |
cairo_set_font_size(cr, 40.0); | |
switch (align) { | |
case 1: | |
cairo_move_to(cr, 0, 50.0); | |
break; | |
case 2: | |
cairo_text_extents(cr, TEXT, &extends); | |
cairo_move_to(cr, 800/2 - extends.width/2, 110.0); | |
break; | |
case 3: | |
cairo_text_extents(cr, TEXT, &extends); | |
cairo_move_to(cr, 800 - extends.width, 170.0); | |
break; | |
} | |
cairo_show_text(cr, TEXT); | |
} | |
int main(int argc, char *argv[]) | |
{ | |
GtkWidget *window; | |
GtkWidget *darea; | |
gtk_init(&argc, &argv); | |
window = gtk_window_new(GTK_WINDOW_TOPLEVEL); | |
darea = gtk_drawing_area_new(); | |
gtk_container_add(GTK_CONTAINER(window), darea); | |
g_signal_connect(G_OBJECT(darea), "draw", | |
G_CALLBACK(on_draw_event), NULL); | |
g_signal_connect(window, "destroy", | |
G_CALLBACK(gtk_main_quit), NULL); | |
gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); | |
gtk_window_set_default_size(GTK_WINDOW(window), 800, 240); | |
gtk_window_set_title(GTK_WINDOW(window), "GTK window"); | |
gtk_widget_show_all(window); | |
gtk_main(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment