[Python] How to change cairo context source color for grayscale images

Discussão em 'Python' iniciado por Stack, Maio 28, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to create images in greyscale using Cairo, however, I am having issues controlling the pixel intensity of the pen.

    For example, in an RGB color image, I would use this code to paint the background a shade of red with a pixel intensity of 127 in the red channel:

    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()


    I can't find any equivalent code for a grayscale image. I can't simply use the alpha channel because then I can't draw circles over rectangles. For example, take the below code snippet, where I would like to have:

    • A grey background
    • A black circle on top of the grey background

    surface = cairo.ImageSurface(cairo.FORMAT_A8, WIDTH, HEIGHT)
    ctx = cairo.Context(surface)
    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()


    In the above code, the black circle won't appear because its alpha channel is lower than the gray background. How can I fix this?

    Continue reading...

Compartilhe esta Página