Found at: http://publish.ez.no/article/articleprint/87/ |
Xlib tutorial 1 - painting colors, graphics contexts and fonts |
Have you ever wondered what is going on behind the scenes of X11 windowmanageres and toolkits? Here is a chance to get into native X programming with Xlib.
|
| Hello world! |
const char *display_name;
if( ( display_name = (char *) getenv("DISPLAY") ) == NULL )
display_name = "";
/* Open a connection to the X server */
Display *dpy = XOpenDisplay( display_name );
if( !dpy )
{
// BSOD: we have no display.
printf( "Cannot not open display %s\n", XDisplayName( display_name ) );
exit( 1 );
}
|
int screen = DefaultScreen( dpy );
Window root = RootWindow( dpy, screen );
|
Colormap colmap = DefaultColormap( dpy, screen );
XColor dummy, black, red;
XAllocNamedColor( dpy, colmap, "black", &black, &dummy );
XAllocNamedColor( dpy, colmap, "red", &red, &dummy );
// create a window that we can draw on.
Window win = XCreateSimpleWindow( dpy, root, 100, 100, 200, 200, 0, black.pixel, black.pixel );
// map the window (that is, show it)
XMapWindow( dpy, win );
|
XFontStruct *font = XLoadQueryFont( dpy, "fixed" );
if( !font )
{
printf("Frekko: Error, couldn't load font\n" );
exit( 1 );
}
XGCValues gv;
gv.function = GXcopy; // paint with src color only.
gv.line_width = 3;
gv.foreground = red.pixel; // foreground is the color reds pixel value.
gv.background = red.pixel; // background is the color reds pixel value.
gv.font = font->fid;
GC gc = XCreateGC( dpy, root, GCFunction | GCLineWidth | GCForeground | GCBackground | GCFont, &gv );
|
// get the geometry of our window, the windowmanager might have changed it.
XWindowAttributes attr;
XGetWindowAttributes( dpy, win, &attr );
int w = attr.width, h = attr.height;
// Draw a big fat cross that covers the whole window.
XDrawLine( dpy, win, gc, 0, 0, w, h );
XDrawLine( dpy, win, gc, 0, h, w, 0 );
const char *text = "Hello world";
// fetch the height of the font, and the width of the text.
int fontHeight = font->ascent + font->descent; // max height above and below baseline
int textWidth = XTextWidth( font, text, strlen( text ) );
// center the text at the top of the window
XDrawString( dpy, win, gc, (w - textWidth)/2, fontHeight, text, strlen( text ) );
XFlush( dpy );
|
while(true)
{
// sleep here, so we won't use 100% cpu.
sleep(10);
break; // quit after 10 seconds
}
XFreeFont( dpy, font );
XFreeGC( dpy, gc );
XCloseDisplay( dpy );
|
Attached files: