alpha blending in gtk

2020-04-15 13:20发布

问题:

How can you draw semi-transparent primitives such as filled polygons to a Drawable in GTK?

Its 2010, and I google isn't finding how to put an alpha value into a colour for me. What am I missing?

回答1:

Use gtk.gdk.Drawable.cairo_create() and operate on the returned gtk.gdk.CairoContext. See documentation. Cairo is a generic vector 2D library that is used in GTK+ since many versions ago; GDK drawing primitives are deprecated in its favor (though not the whole GDK).



回答2:

Here is actual source code to do it. I just wanted to gray out the entire pixbuf, but to do a shape you'd just have to use the appropriate path methods:

def getBlendedPixbuf(pixbuf, (r,g,b,a)):
    """Turn a pixbuf into a blended version of the pixbuf by drawing a
    transparent alpha blend on it."""
    pixbuf = pixbuf.copy()
    #convert pixbuf to Drawable:
    visual = gtk.gdk.visual_get_best()
    screen = visual.get_screen()
    cmap = screen.get_default_colormap()

    w,h = pixbuf.get_width(), pixbuf.get_height()
    drawable = gtk.gdk.Pixmap(
        None, w, h, visual.depth)
    gc = drawable.new_gc()
    drawable.draw_pixbuf(
        gc, pixbuf, 0,0,0,0,-1,-1)

    #do all the drawing on it
    cc = drawable.cairo_create()
    cc.set_source_rgba(r,g,b,a)
    cc.paint()

    #put it back into a pixbhf
    pixbuf.get_from_drawable(
        drawable,cmap,0,0,0,0,w,h)
    return pixbuf