如何使用x11窗口背景加载bmp文件

时间:2013-02-21 05:19:01

标签: c++ linux x11 embedded-linux xlib

我尝试使用bmp文件在x11窗口中设置背景图像。我使用XReadBitmapFile但它无法正常工作。我如何使用bmp文件来设置x11窗口背景。提前致谢

1 个答案:

答案 0 :(得分:2)

XReadBitmapFile仅用于读取.xbm文件。我们需要的是一个用于读取BMP文件的库,一种可能性是ImLib2,它可以读取多种类型的文件,并且可以很好地与Xlib一起使用。

以下是使用它的一个长期例子:

/* displays an image or sets root background
 * PUBLIC DOMAIN - CC0 http://creativecommons.org/publicdomain/zero/1.0/
 * J.Mayo 2013
 *
 * gcc -Wall -W -g3 -o xrootbg xrootbg.c -lX11 -lImlib2
 *
 */
#include <stdio.h>
#include <X11/Xlib.h>
#include <Imlib2.h>

int main(int argc, char **argv)
{
    Imlib_Image img;
    Display *dpy;
    Pixmap pix;
    Window root;
    Screen *scn;
    int width, height;
    const char *filename = NULL;

    if (argc < 2)
        goto usage;
    filename = argv[1];

    img = imlib_load_image(filename);
    if (!img) {
        fprintf(stderr, "%s:Unable to load image\n", filename);
        goto usage;
    }
    imlib_context_set_image(img);
    width = imlib_image_get_width();
    height = imlib_image_get_height();

    dpy = XOpenDisplay(NULL);
    if (!dpy)
        return 0;
    scn = DefaultScreenOfDisplay(dpy);
    root = DefaultRootWindow(dpy);

    pix = XCreatePixmap(dpy, root, width, height,
        DefaultDepthOfScreen(scn));

    imlib_context_set_display(dpy);
    imlib_context_set_visual(DefaultVisualOfScreen(scn));
    imlib_context_set_colormap(DefaultColormapOfScreen(scn));
    imlib_context_set_drawable(pix);

    imlib_render_image_on_drawable(0, 0);
    XSetWindowBackgroundPixmap(dpy, root, pix);
    XClearWindow(dpy, root);

    while (XPending(dpy)) {
        XEvent ev;
        XNextEvent(dpy, &ev);
    }
    XFreePixmap(dpy, pix);
    imlib_free_image();
    XCloseDisplay(dpy);
    return 0;
usage:
    fprintf(stderr, "usage: %s <image_file>\n", argv[0]);
    return 1;
}