2012-05-01 41 views
0

這是先前問題的一個重複,但澄清。 因爲我之前沒有答案,我想在這個新的簡潔的問題中重新提問 會更好。如何保存分層pyCairo pyGTK圖像

我成功地生成了一個透明窗口。 我成功地在窗口內生成了紅色圓圈的半透明疊加圖像。 我成功生成了紅色圓圈內的小黑方塊的不透明覆蓋圖像。 如何將我在窗口中看到的內容保存到PNG文件中。 我已經搜索了stackoverflow,nullege和谷歌沒有成功。

以下代碼的最後兩行顯示我的保存失敗。 使用什麼代碼可以將其替換爲查看包含我在屏幕上看到的PNG的PNG。

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) 

回答

1

它看起來像你正在渲染的圖像表面,它沒有任何內容。您應該渲染窗口上下文的表面,這是您繪製圖形的地方。試試這個:

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 
+0

非常感謝。那就是訣竅。 – jlettvin

+0

我的錯誤是爲了聲明這個固定的。出現半透明且不透明的標記,但不顯示下方窗口的背景。由於標記是爲了裝飾背景,因此遺漏背景使得結果幾乎無用。還有一個額外的步驟可以捕捉到這一點嗎? – jlettvin