Search code examples
c++graphicspixel

How to do pixel manipulations in C++? - Linux


My Goal:

I would like to independently manipulate pixels color of a created window like a bitmap picture. I would prefer a native library targeting Ubuntu -> Linux. It may be working with a function like:

SetPixel(int x,int y,int Color) {

  //Some code that set the color of one pixel by his coordinates x and y

  return 0;//May return an error
}

It will set the color of a pixel in the window by his position

Problems:

I already tried many tutorials (which are using Graphics.h or Windows.h) , but none of them were working on my computer, I could be doing something wrong but what I found isn't explicit. Anyway, I wouldn't know how to download a library without instructions. I believe that it doesn't work on Linux.

SDL2 isn't native of Linux. by the way

If any clarification is needed, please add a comment or suggest an edit


Solution

  • For me, the easy solution something similar to the code below

    #include <X11/Xlib>
    bool SetPixel(uint16_t X,uint16_t Y,uint32_t Color){
        XSetForeground(_Display,_GraphicCTX,Color);
        XDrawPoint(_Display,_Window,_GraphicCTX,X,Y);
        return true;
    }
    
    bool Setup(){ //Use it first to make every graphical manipulations working :)
        Display=XOpenDisplay(0);//Create a display
        Window=XCreateSimpleWindow(Display,DefaultRootWindow(Display),0,0,480,360,0,0,0);   //Create a Window
        XMapWindow(Display,Window);//Make the Window visible
        GraphicCTX=XCreateGC(Display,Window,0,NIL);//Create a Graphics Context
        //v Wait for a MapNotify XEvent for next commands
        XSelectInput(Display,Window,StructureNotifyMask);
        while(1){
            XEvent E;
            XNextEvent(Display,&E);
            if(E.type==MapNotify)break;
        }
        return true;
    }
    

    I used X11 as it is the native graphical protocol of Linux.

    In fact, I made a library to make everything simpler with a class.

    The setup function is required to be run before any graphical operations else it won't do anything!

    This can work, but for advanced development, you'll need play with images and more! There is a very great manual for Xlib!