用Xcb而不是Xlib抓取像素的颜色

Grab the color of a pixel with Xcb instead of Xlib

本文关键字:抓取 像素 颜色 Xlib Xcb      更新时间:2023-10-16

我使用几个窗口管理器,如果我理解正确,他们使用xlib。(真棒,打开盒,通量盒...

我使用以下代码来检测像素中的"RED"数量:

#include <iostream>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
using namespace std;
int main(int argc, char *argv[]){
    XColor c;
    Display *d = XOpenDisplay((char *) NULL);
    int RED;
    int x=atoi(argv[1]);
    int y=atoi(argv[2]);
    XImage *image;
    image = XGetImage (d, RootWindow (d, DefaultScreen (d)), x, y, 1, 1, AllPlanes, XYPixmap);
    c.pixel = XGetPixel (image, 0, 0);
    XFree (image);
    XQueryColor (d, DefaultColormap(d, DefaultScreen (d)), &c);
    RED=c.red/256;
    cout << RED;
}

但它总是返回 0 与我的i3-gaps窗口管理器。(与其他人合作(

我想这是因为i3不使用Xlib而是使用Xcb

如果是这样,我怎样才能用Xcb实现同样的事情?(与 Xlib 语法向后兼容的东西?

我刚刚用#include <xcb/xcb.h>替换了#include <X11/Xlib.h>

了不起。。。

这是一个纯 C 示例,但它也可以在C++中使用。请注意,我没有进行任何错误检查,但绝对应该为演示以外的任何东西添加它。

#include <stdio.h>
#include <xcb/xcb.h>
#include <xcb/xcb_image.h> 
#include <inttypes.h>
// https://refspecs.linuxfoundation.org/LSB_5.0.0/LSB-Desktop-generic/LSB-Desktop-generic.html
#define AllPlanes   ((unsigned long)~0L)
#define XYPixmap    1
int main() {
    // Location of pixel to check
    int16_t x = 0, y = 0;
    
    // Open the connection to the X server. Use the DISPLAY environment variable
    int screen_idx;
    xcb_connection_t *conn = xcb_connect(NULL, &screen_idx);
    // Get the screen whose number is screen_idx
    const xcb_setup_t *setup = xcb_get_setup(conn);
    xcb_screen_iterator_t iter = xcb_setup_roots_iterator(setup);  
    // We want the screen at index screen_idx of the iterator
    for (int i = 0; i < screen_idx; ++i)
        xcb_screen_next(&iter);
    xcb_screen_t *screen = iter.data;
    
    // Get pixel
    uint32_t pixel = xcb_image_get_pixel(xcb_image_get(conn, screen->root, x, y, 1, 1, AllPlanes, XYPixmap), 0, 0);
    printf("%d", pixel);
    return 0;
}