简体   繁体   中英

How to save layered pyCairo pyGTK image

This is sort of a repeat of an earlier question, but clarified. Since I got no answer before, I figured it would be better to re-ask it in a new and more succinct question.

I succeed in generating a transparent window. I succeed in generating a semi-transparent overlay image of a red circle within the window. I succeed in generating an opaque overlay image of tiny black squares within the red circle. How do I save to a PNG file what I see in the window. I have searched stackoverflow, nullege, and google without success.

The last two lines of the code below show my failing save. With what code can I replace this to see a PNG containing what I see on the screen.

import pygtk
pygtk.require('2.0')
import gtk, cairo
from math import pi

# Window setup
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_decorated(True)
window.set_app_paintable(True)
window.set_colormap(window.get_screen().get_rgba_colormap())
window.realize()
window.show()
window.set_flags(gtk.HAS_FOCUS | gtk.CAN_FOCUS)
window.grab_focus()

# Cairo transparent setup
cr = widget.window.cairo_create()
cr.set_operator(cairo.OPERATOR_CLEAR)
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 201, 201)
cr.rectangle(0, 0, 201, 201)
cr.fill()

# Cairo semi-transparent setup
cr.set_operator(cairo.OPERATOR_OVER)
cr.set_source_rgba(0.5, 0.0, 0.0, 0.5)
cr.arc(100, 100, 100, 0, pi*2)
cr.fill()

# Cairo opaque setup
cr.set_operator(cairo.OPERATOR_OVER)
width = 3
r, g, b, a = (0.0,0.0,0.0,1.0)
cr.set_source_rgba(r,g,b,a)
cr.rectangle(-1, -1, 3, 3)
cr.fill()

# Restore default Cairo conditions
cr.set_operator(cairo.OPERATOR_OVER)

# Save layered image to a png image file
with open('layered.png', 'w+') as png:
    surface.write_to_png(png)

It looks like you are rendering the image surface, which does not have any content in it. You should instead be rendering the surface of the window context, which is where you are doing your drawing. Try this instead:

surface = cr.get_group_target() # get the surface being drawn to the window via your context
surface.write_to_png(png) # write the surface to a file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM