使用Xlib更改绘图颜色

3

我将使用Xlib编写一个应用程序。我会像这样设置窗口的前景色:

XSetForeground (dpy, gc, WhitePixel (dpy, scr));

但现在我需要将绘图颜色更改为其他颜色,我最初想要这样做:
void update_window (Display* d, Window w, GC gc, Colormap cmap) 
{
    XWindowAttributes winatt;
    XColor bcolor;
    char bar_color[] = "#4E4E4E";

    XGetWindowAttributes (d, w, &winatt);

    XParseColor(d, cmap, bar_color, &bcolor);
    XAllocColor(d, cmap, &bcolor);

    // Draws the menu bar.
    XFillRectangle (d, w, gc, 0, 0, winatt.width, 30);

    XFreeColormap (d, cmap);
}

但这并不起作用。那么XParseColor和XAllocColor是做什么的?我是否需要再次使用XSetForeground来更改颜色?

3个回答

4
你需要使用 XSetForeground。尝试像这样做:
XColor xcolour;

// I guess XParseColor will work here
xcolour.red = 32000; xcolour.green = 65000; xcolour.blue = 32000;
xcolour.flags = DoRed | DoGreen | DoBlue;
XAllocColor(d, cmap, &xcolour);

XSetForeground(d, gc, xcolour.pixel);
XFillRectangle(d, w, gc, 0, 0, winatt.width, 30);
XFlush(d);

此外,我认为您不能使用那个颜色字符串。请查看this页面。

A numerical color specification consists of a color space name and a set of values in the following syntax:

<color_space_name>:<value>/.../<value>

The following are examples of valid color strings.

"CIEXYZ:0.3227/0.28133/0.2493"
"RGBi:1.0/0.0/0.0"
"rgb:00/ff/00"
"CIELuv:50.0/0.0/0.0"

编辑/更新:正如@JoL在评论中提到的那样,您仍然可以使用旧语法,但不建议使用

为了向后兼容,RGB设备支持较旧的语法,但不鼓励继续使用。该语法是一个初始井号字符,后跟数字规范,格式如下之一:


此外,我认为您不能使用该颜色字符串。这显然是为了“向后兼容”而由Xlib支持的。请在官方文档中检查。我想他们当时没料到这种语法会成为指定颜色的一个事实标准。 - JoL

3
//I write additional function _RGB(...) where r,g,b is components in range 0...255
unsigned long _RGB(int r,int g, int b)
{
    return b + (g<<8) + (r<<16);
}


void some_fun()
{
  //sample set color, where r=255 g=0 b=127
  XSetForeground(display, gc, _RGB(255,0,127));

  //draw anything
  XFillRectangle( display, window, gc, x, y, len, hei );

}

这对于TrueColor视觉效果非常好。它能在可用位深度较小的视觉上工作吗? - Dúthomhas

1
所有颜色更改都是针对特定的GC进行的。然后使用该GC进行绘图。是的,XSetForeground 是最方便的方法。
如果您经常使用几种颜色,则可以拥有多个GC。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接