如何更改灰度图像的 cairo 上下文源颜色

How to change cairo context source color for grayscale images

我正在尝试使用 Cairo 创建灰度图像,但是我在控制笔的像素强度方面遇到了问题。

例如,在 RGB 彩色图像中,我将使用此代码在红色通道中将背景绘制为红色,像素强度为 127

surface = cairo.ImageSurface(cairo.FORMAT_RGB24, WIDTH, HEIGHT)
ctx = cairo.Context(surface)
ctx.set_source_rgb(.5, 0, 0)
ctx.rectangle(0, 0, WIDTH, HEIGHT)
ctx.fill()

我找不到灰度图像的任何等效代码。 我不能简单地使用 alpha 通道,因为这样我就不能在矩形上画圆。例如,采用下面的代码片段,我希望有:

在上面的代码中,黑色圆圈不会出现,因为它的alpha通道低于灰色背景。我该如何解决这个问题?

In the above code, the black circle won't appear because it's alpha channel is lower than the gray background.

默认的运算符是OVER,覆盖东西。如果你有一些完全透明的覆盖层,那么这个覆盖层是不可见的。所以,这不是因为较低的 alpha 通道。如果您的 alpha 通道略高,比如 0.5 和 0.1,则结果图像中的 alpha 通道值将约为 0.6。

How can I fix this?

surface = cairo.ImageSurface(cairo.FORMAT_A8, WIDTH, HEIGHT)
ctx = cairo.Context(surface)
// I added the following line, but I am not sure about the syntax.
// In C, this would by cairo_set_operator(ctx, CAIRO_OPERATOR_SOURCE);
ctx.set_operator(cairo.OPERATOR_SOURCE)
ctx.set_source_rgba(0, 0, 0, 0.5)
ctx.rectangle(0, 0, WIDTH, HEIGHT)
ctx.fill()
ctx.set_source_rgba(0, 0, 0, 0.0)
ctx.arc(WIDTH//2, HEIGHT//2, r, 0, 2*math.pi)
ctx.fill()