如何在开罗表面绘制任何GTK小部件 [英] How to draw any GTK widget on top of Cairo surface
问题描述
我想保存一个GTK窗口的外观,以及它包含到PNG或PDF文件中的所有按钮和其他小部件。开罗支持在这些表面上绘图。
我可以以某种方式请求一个GTK小部件在开罗表面上绘制自己?
代码示例将非常感谢,因为我是GTK和开罗的新手。
Python是我选择的语言。
ptomato说。如果您需要在屏幕外执行此操作,请使用Gtk.OffscreenWindow,否则只需获取Gdk窗口和窗口小部件的分配即可将其剪下。这是一个可用于获取任何窗口小部件快照的片段。如下面的代码所示,您还可以使用Gtk.Widget.draw()方法在Cairo上下文中呈现它。
from gi.repository import Gtk
import cairo
WINDOW_WIDTH,WINDOW_HEIGHT = 400,300
window = Gtk.OffscreenWindow()
window.set_default_size (WINDOW_WIDTH,WINDOW_HEIGHT)
window.show()
canvas = Gtk.HBox()
window.add(canvas)
canvas.show()
button = Gtk.Button(Hello World!)
canvas.add(button)
button.show()
#这是必需的,否则截图是黑色的:
,而Gtk.events_pending():
Gtk.main_iteration()
surf = cairo.ImageSurface(cairo.FORMAT_ARGB32,
WINDOW_WIDTH, WINDOW_HEIGHT)
cr = cairo.Context(surf)
canvas.draw(cr)
surf.write_to_png('test.png')
$ b您可以暂时将一个小部件(如ptomato所说)重新分配给此Gtk.OffscreenWindow,以便使s
original_parent = canvas.get_parent()
canvas.reparent(offscreen_window)
#做快照
canvas.reparent(original_parent)
I would like to save the looks of a GTK window, and all the buttons and other widgets it contains to a PNG or PDF file. Cairo supports drawing on such surfaces. Could I somehow ask a GTK widget to draw itself on Cairo surface? A code sample would be much appreciated, since I am a newcomer to both GTK and Cairo. Python is my language of choice.
解决方案What ptomato says. Use a Gtk.OffscreenWindow if you need to do it off screen, otherwise just get the Gdk window and the widget's allocation to clip it. Here is a snippet that can be used to get a snapshot of any widget. As the following code shows, you can also use the Gtk.Widget.draw() method to render it in the Cairo context.
from gi.repository import Gtk import cairo WINDOW_WIDTH, WINDOW_HEIGHT = 400, 300 window = Gtk.OffscreenWindow() window.set_default_size(WINDOW_WIDTH, WINDOW_HEIGHT) window.show() canvas = Gtk.HBox() window.add(canvas) canvas.show() button = Gtk.Button("Hello World!") canvas.add(button) button.show() # this is needed, otherwise the screenshot is black: while Gtk.events_pending(): Gtk.main_iteration() surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, WINDOW_WIDTH, WINDOW_HEIGHT) cr = cairo.Context(surf) canvas.draw(cr) surf.write_to_png('test.png')
You can temporarily reparent a widget (as ptomato said) to this Gtk.OffscreenWindow, in order to make the snapshot.
original_parent = canvas.get_parent() canvas.reparent(offscreen_window) # do snapshot canvas.reparent(original_parent)
这篇关于如何在开罗表面绘制任何GTK小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!