Xlib tutorial part 2 -- Lines

by Alan at Mon 19th Jan 2009 1:00AM EST
updated Sat 24th Jan 2009 6:37PM EST


A blank black window is not very interesting. We want to place some thing in the window. Well, just like in real life you need a pen or pencil to draw on a blank piece of paper, our program needs a pen to draw on our window.

First we'll add a new GC pen, and a XGCValues structure for choosing what style of pen we want.

	GC pen;
	XGCValues values;

Then, after we've created the window we can create the pen,

	/* create the pen to draw lines with */
	values.foreground = WhitePixel(dpy, screen_num);
	values.line_width = 1;
	values.line_style = LineSolid;
	pen = XCreateGC(dpy, win, GCForeground|GCLineWidth|GCLineStyle,&values);

This particular pen that we've chosen, draws with a white ink. Makes one pixel wide lines and draws the line solidly. There are a lot of options on that you can choose. Look at the man page for XGCValues to see all the different pieces of style information you can choose. For our purposes the three we've got is enough.

	/* as each event that we asked about occurs, we respond.  In this
	 * case, if a piece of window was exposed we draw two diagonal lines
		XNextEvent(dpy, &ev);
		case Expose:
			XDrawLine(dpy, win, pen, 0, 0, width, height);
			XDrawLine(dpy, win, pen, width, 0, 0, height);
		case ConfigureNotify:
			if (width != ev.xconfigure.width
					|| height != ev.xconfigure.height) {
				width = ev.xconfigure.width;
				height = ev.xconfigure.height;
				XClearWindow(dpy, ev.xany.window);
				printf("Size changed to: %d by %d
", width, height);
		case ButtonPress:
			return 0;

The complete code can be found in xtut2.c

This is an extra 13 lines. This program is not nearly as easy to do in HTML.

Things to try:

Comments are closed.