commit 251edb4ded6f864024e63d2388744b045cc26b22
parent 55bc884e3a04655cc59702fa0cc23074a65dc49c
Author: lostd <lostd@2f30.org>
Date: Sun, 8 Dec 2013 14:15:07 +0200
Xlib and cairo example code to draw a png image
Diffstat:
A | see/Makefile | | | 13 | +++++++++++++ |
A | see/see.c | | | 99 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
2 files changed, 112 insertions(+), 0 deletions(-)
diff --git a/see/Makefile b/see/Makefile
@@ -0,0 +1,13 @@
+LOCALBASE = /usr/local
+X11BASE = /usr/X11R6
+
+CFLAGS = -I$(LOCALBASE)/include -I$(X11BASE)/include
+LDFLAGS = -L$(LOCALBASE)/lib -L$(X11BASE)/lib
+LDLIBS = -lX11 -lcairo
+
+BIN = see
+
+all: $(BIN)
+
+clean:
+ rm -f $(BIN)
diff --git a/see/see.c b/see/see.c
@@ -0,0 +1,99 @@
+#include <err.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <X11/Xlib.h>
+#include <cairo/cairo.h>
+#include <cairo/cairo-xlib.h>
+
+/* draw a png image inside an xlib window using cairo */
+
+int
+main(int argc, char *argv[])
+{
+ Display *dpy;
+ Window root, win;
+ XEvent e;
+ int scr;
+ cairo_surface_t *cs, *img;
+ cairo_t *c;
+ int winw, winh;
+ int imgw, imgh;
+ char *imgpath;
+
+ imgpath = argv[1];
+ if (imgpath == NULL) {
+ fprintf(stderr, "usage: see image.png\n");
+ exit(1);
+ }
+
+ /* load image and get dimantions */
+ img = cairo_image_surface_create_from_png(imgpath);
+ if (cairo_surface_status(img) != CAIRO_STATUS_SUCCESS)
+ errx(1, "load image");
+ imgw = cairo_image_surface_get_width(img);
+ imgh = cairo_image_surface_get_height(img);
+
+ /* init screen and get dimensions */
+ dpy = XOpenDisplay(NULL);
+ if (dpy == NULL)
+ errx(1, "open display");
+ scr = DefaultScreen(dpy);
+ winw = DisplayWidth(dpy, scr);
+ winh = DisplayHeight(dpy, scr);
+
+ /* resize window if img is smaller */
+#define MIN(x, y) ((x) < (y) ? (x) : (y))
+ winw = MIN(winw, imgw);
+ winh = MIN(winh, imgh);
+#undef MIN
+
+ /* create window */
+ root = RootWindow(dpy, scr);
+ win = XCreateSimpleWindow(dpy, root, 0, 0, winw, winh, 0,
+ BlackPixel(dpy, scr), BlackPixel(dpy, scr));
+
+ /* register for events */
+ XSelectInput(dpy, win, ExposureMask | KeyPressMask);
+
+ /* name window */
+ XStoreName(dpy, win, imgpath);
+
+ /* draw window */
+ XMapWindow(dpy, win);
+
+ /* create surface in window */
+ cs = cairo_xlib_surface_create(dpy, win, DefaultVisual(dpy, scr),
+ winw, winh);
+ c = cairo_create(cs);
+
+ /* put image on surface centered */
+ cairo_set_source_surface(c, img,
+ (winw - imgw) / 2, (winh - imgh) / 2);
+
+ while (1) {
+ XNextEvent(dpy, &e);
+
+ switch (e.type) {
+ case Expose:
+ /* redraw if damaged */
+ if (e.xexpose.count < 1)
+ cairo_paint(c);
+ break;
+ case KeyPress:
+ /* quit on q pressed */
+ if (XLookupKeysym(&(e.xkey), 0) ==
+ XStringToKeysym("q"))
+ goto out;
+ break;
+ }
+ }
+
+out:
+ /* free */
+ cairo_destroy(c);
+ cairo_surface_destroy(cs);
+ cairo_surface_destroy(img);
+ XCloseDisplay(dpy);
+
+ return 0;
+}