Xlib tutorial part 4 -- Text

by Alan at Mon 2nd Feb 2009 1:00AM EST

Hello,

Colour is great, but now it might be interesting to display some text. Again X has a large text management system to be able to handle many fonts and sizes. So, we'll start with the new variables since the last section.


	...
	char *fontname;
	XFontStruct *font;
	char * text = "Hi!";
	int text_width;
	int textx, texty;
	...

	

That's two variables to remember the font and the information about it. Then one to hold the text we want to show. The other three are to hold calculated numbers to specify where the text will display in the window.


	...
	width = 400; /* This time a bigger window */
	height = 400;
	...
	fontname = "-*-helvetica-*-10-*";
	font = XLoadQueryFont(dpy, fontname);
	if (!font) {
		fprintf(stderr, "unable to load preferred font: %s using fixed
", fontname);
		font = XLoadQueryFont(dpy, "fixed");
	}
	...
	values.font = font->fid;
	pen = XCreateGC(dpy, win, GCForeground|GCLineWidth|GCLineStyle|GCFont,&values);
	text_width = XTextWidth(font, text, strlen(text));
	...
	

I've increased the size of the window so we can see what's going on. XLoadQueryFont() does a round trip to ask the display server to ask if it has the given font. Remember the concept of round trip as that will come up later when we start thinking about how quick our application is. So far, we don't have much to worry about, the application should come up almost instantaneously, even over slow links because we're not doing a lot of them before entering our event (main) loop.

The other thing that we've done here is to add the font to the GC(pen) so that it knows how to draw text when we tell it to do so. We've also stopped to calculate the width the string is going to take.


		...
		case Expose:
			XDrawLine(dpy, win, pen, 0, 0, width/2-text_width/2, height/2);
			XDrawLine(dpy, win, pen, width, 0, width/2+text_width/2, height/2);
			XDrawLine(dpy, win, pen, 0, height, width/2-text_width/2, height/2);
			XDrawLine(dpy, win, pen, width, height, width/2+text_width/2, height/2);
   			textx = (width - text_width)/2;
   			texty = (height + font->ascent)/2;
   			XDrawString(dpy, ev.xany.window, pen, textx, texty, text, strlen(text));
			break;
		...
	

Here we've moved the lines so that they don't run right through the middle of the window, and instead placed the text there. Text is normally placed such that where you were starting if you are writing cursively is the text's starting point. This generally means the bottom left of the first letter of the text. Though it changes for some scripts. textx and texty are calculated such that the text should be centered in window.

Things to try:

Comments are closed.