2015-07-13 19 views
0

我想爲我在X11圖形窗口上繪製的不同對象添加不同的顏色。如何更改X11圖形編程中不同對象的圖形顏色?

示例:這是我們用來指定窗口顯示顏色以及因此繪製的對象的通用代碼。

XAllocNamedColor(display,DefaultColormap(display,screen),「red」,& color,& dummy);

在下面顯示的代碼中,直線和矩形都以紅色顯示。有沒有辦法以紅色和矩形顯示藍色的線?我需要在代碼中做什麼更改?

代碼:

#include <stdio.h> 
#include <X11/Xlib.h> 
#include <unistd.h> 
#include <math.h> 
#include "time.h" 
#include "sys/time.h" 


Display *display; 
Window window; 
XSetWindowAttributes attributes; 
XGCValues gr_values; 
XFontStruct *fontinfo; 
GC gr_context; 
Visual *visual; 
int depth; 
int screen; 
XEvent event; 
XColor color, dummy; 

main (argc, argv) 
char *argv[]; 
int  argc; 
{ 


display = XOpenDisplay(NULL); 
screen = DefaultScreen(display); 
visual = DefaultVisual(display,screen); 
depth = DefaultDepth(display,screen); 
attributes.background_pixel = XWhitePixel(display,screen); 

window = XCreateWindow(display,XRootWindow(display,screen), 
         0, 0, 1250, 1200, 5, depth, InputOutput, 
         visual ,CWBackPixel, &attributes); 
XSelectInput(display,window,ExposureMask | KeyPressMask) ; 
fontinfo = XLoadQueryFont(display,"6x10"); 

XAllocNamedColor(display, DefaultColormap(display, screen),"red", 
        &color,&dummy); 

gr_values.font = fontinfo->fid; 
gr_values.foreground = color.pixel; 


gr_context=XCreateGC(display,window,GCFont+GCForeground, &gr_values); 


XFlush(display); 
XMapWindow(display,window); 
XFlush(display); 

while(1){ 
    XNextEvent(display,&event); 

    switch(event.type){ 
    case Expose: 

     XDrawLine(display,window,gr_context,800,800, 400, 450); 

     XDrawRectangle(display,window,gr_context,i+10,j+10, 200, 150); 

     break; 

    case KeyPress: 
     XCloseDisplay(display); 
     exit(0); 

    } 
    } 
} 

回答

1

在X11,則可以將顏色添加到圖形上下文(GC),作爲參數傳遞XDrawLine,等你的程序可能調用XCreateGC創建一個圖形上下文。您可以通過設置其掩模GCForeground和/或GCBackground來設置前景和/或背景顏色,並在創建時將XAllocNamedColor(在XColor值中)獲得的Pixel值複製到XGCValues的前景/背景結構成員中GC。

XColor值具有顏色的R/G/B分解(回答後續問題)。您可以使用XAllocColor將R/G/B值轉換爲像素值(例如,請參閱Read Only Colorcells: An easy Example)。

+0

嗨托馬斯,謝謝。我也把代碼放在了問題中。如您所見,兩個結構都以紅色顯示。我應該對代碼進行哪些更改,以紅色顯示直線並用藍色顯示矩形我們可以這麼說嗎? – beginner

+0

您可以使用「XChangeGC」更新圖形上下文,或者爲每種顏色製作兩個圖形上下文。請記住,通過調用X服務器完成對GC的更改(並且X服務器可以緩存「少數」GC)。 –

+0

謝謝。那麼,我無法按照你之前的回答來回答我的後續問題。我在說如果我需要繪製點讓我們說使用XDrawPoint(),我只是給像素座標輸入。但是,如果我想打印每個具有特定像素值的點,即R,G,B,如何編寫該特定部分的代碼,請給我一個提示? – beginner