Rendering Text on Linux with Xft
Diving into the innermost workings of the Linux operating system is a pretty interesting challenge. Pretty much nobody nowadays implements anything with raw X11 anymore. They use QT, SDL, or for drawing Cairo, with Pango for text rendering. The thing is, all of these libraries use X11 as the backend. I need full control and understanding over what my code is doing, so I've opted to cut out the middleman and go directly to the innermost core of Linux.
Today I improved our text rendering by implementing the XFT extension for X11. This library uses FreeType to make True-type Fonts renderable in a Linux window. Although the documentation looks intimidating, usage is actually very simple if you already have a renderable X11 window working.
First, you create an XFT drawable:
XftDraw* xftdraw = XftDrawCreate(display,drawable,DefaultVisual(display,0),DefaultColormap(display,0));
Now, load your font:
XftFont* xfont = XftFontOpen(Window::display, DefaultScreen(Window::display), XFT_FAMILY, XftTypeString, "ubuntu", XFT_SIZE, XftTypeDouble, 10.0, NULL);
Drawing is fairly straightforwardish:
XRenderColor xrcolor; XftColor xftcolor; xrcolor.red = 65535; xrcolor.green = 65535; xrcolor.blue = 65535; xrcolor.alpha = 65535; XftColorAllocValue(display,DefaultVisual(display,0),DefaultColormap(display,0),&xrcolor,&xftcolor); XftDrawString8(xftdraw, &xftcolor, xfont, x, y + GetFontHeight(), (unsigned char*)text.c_str(), text.size()); XftColorFree(display,DefaultVisual(display,0),DefaultColormap(display,0),&xftcolor);
And if you need to set clipping it's easy:
XftDrawSetClipRectangles(xftdraw,0,0,&xrect,1);
Here is the result, rendered with 11 point Arial font:
As you can see below, sub-pixel antialiasing is used. Character spacing also seems correct:
By using Xft directly we can avoid the extra dependency on Pango, and the resulting text looks great. Next I will be looking at the XRender extension for alpha blending. This would allow us to forgo use of the Cairo graphics library, if it works.
- 2
5 Comments
Recommended Comments